###前提・実現したいこと
下記のコードのようにnew演算子でobjを利用して、delete演算子でobjを消そうとしましたがエラーが発生しています。この場合、どのようにしてobjを消せば良いのでしょうか。
###発生している問題・エラーメッセージ
Main.cpp:10:29: warning: ISO C++11 does not allow conversion from string literal to 'char ' [-Wwritable-strings]
char Worker::CompanyName = "ABC";
^
Main.cpp:21:16: error: use of undeclared identifier 'obj'
delete [] obj;
^
1 warning and 1 error generated.
###ソースコード
<ヘッダー> class Worker{ public: static int no; int num; static char* CompanyName; double salary; char department[100]; char name[100]; Worker(); ~Worker(); Worker(double salary ,char department[100], char name[100]); void ShowData(); void ShowDataPointer(Worker *a); Worker* inputdata(); }; <メイン文> #include <iostream> using namespace std; #include <iostream> #include "string.h" #include "Worker.h" using namespace std; int Worker::no = 0; char* Worker::CompanyName = "ABC"; Worker::Worker(){ this->num = no; this->salary = 0; strcpy(this->department, "NotDefinedDepartment"); strcpy(this->name, "NotDefinedName"); no++; } Worker::~Worker(){ delete [] obj; } Worker::Worker(double salary, char department[100], char name[100]){ this->num = no; this->salary = salary; strcpy(this->department,department); strcpy(this->name,name); no++; } void Worker::ShowData(){ cout << "no = " << this->num << "\n"; cout << "salary = " << this->salary << "\n"; cout << "department = " << this->department << "\n"; cout << "name = " << this->name << "\n"; } void Worker::ShowDataPointer(Worker *a){ cout << "no = " << a->num << "\n"; cout << "salary = " << a->salary << "\n"; cout << "department = " << a->department << "\n"; } Worker* Worker::inputdata(){ Worker* obj = new Worker(); obj->num = no; obj->salary=100; strcpy(obj->department, "inputdata"); strcpy(obj->name, "name_inputdata"); no++; cout << "this is inputdata" << "\n"; obj->ShowData(); cout << "this is end of inputdata" << "\n"; // return &obj; 関数を抜けるとき、アドレスが解法されるので下記のように行う必要がある。 //new で動的にオブジェクトを作成しないと、ほかの値が作成されると前回のメモリ空間の値が、上書きされる。 return obj; } int main(void){ Worker w[3]; Worker w1; Worker* w2; Worker* someone[3]; for(int i=0 ; i<3 ;i++){ w[i].salary = 100; strcpy(w[i].department, "E"); strcpy(w[i].name, "Takayuki"); someone[i] = &w[i]; cout << "salary = " << someone[i]->salary << "\n"; } cout << "---------w2 inputdata;------------" << "\n"; w2 = w1.inputdata(); //w1は関数を抜けたとき、削除されるか、他のオブジェクトの占有され値が変更されるので、objを返すと良い。 cout << "w1 ===== " << &w1 << "\n"; cout << "---------w2.ShowDataPointer();------------" << "\n"; w1.ShowDataPointer(w2); cout << "--------- w2->ShowData();------------" << "\n"; w2->ShowData(); cout << "---------w1.ShowData();------------" << "\n"; w1.ShowData(); cout << "---------w[0].ShowData();------------" << "\n"; w[0].ShowData(); cout << "---------------------" << "\n"; w[1].ShowData(); cout << "---------------------" << "\n"; w[0].ShowDataPointer(&w[0]); }
###補足情報(言語/FW/ツール等のバージョンなど)
paiza.io
回答3件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。