###前提・実現したいこと
下記のコードの中で、関数内で Worker* inputdata();でアドレスを返却し、w2にポインタを返しているのですが、関数内でアドレスが解放されているのにも関わらず、w1.ShowDataPointer(w2);がなぜか動いています。
これはコンパイラの影響でしょうか。ちなみにPaiza.ioを利用しています。
###ソースコード
<ヘッダー文> 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(){ } 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; 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; 関数を抜けるとき、アドレスが解法されるので下記のように行う必要がある。 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"; } w2 = w1.inputdata(); //w1は関数を抜けたとき、削除される。 cout << "w1 ===== " << &w1 << "\n"; cout << "---------w1.ShowDataPointer();------------" << "\n"; w1.ShowDataPointer(w2); cout << "---------w2.ShowData();------------" << "\n"; w2->ShowData(); cout << "---------------------" << "\n"; w1.ShowData(); w[0].ShowData(); cout << "---------------------" << "\n"; w[1].ShowData(); cout << "---------------------" << "\n"; w[0].ShowDataPointer(&w[0]); }
###補足情報(言語/FW/ツール等のバージョンなど)
回答3件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2016/01/20 05:47
2016/01/21 01:25