[問題] copy constructor的問題

看板C_and_CPP (C/C++)作者時間16年前 (2009/03/16 22:46), 編輯推噓2(202)
留言4則, 2人參與, 最新討論串1/2 (看更多)
有點搞不太懂copy construtor的用途 我知道的大概是 物件傳給函數時 會複製一個物件 而有可能因為改變此復製物件(ex:delete)時 而改變了原本物件 應該是降對吧...? 以下是一個範例 上面程式碼沒有使用copy constructor 而下面程式碼有 不懂的是為什麼第一個程式碼印出 1 2 0 4072544 而加了copy constructor可以解決此問題 我有把output寫在程式碼下方 謝謝! =========沒有使用copy constructor================ #include <cstdlib> #include <iostream> using namespace std; class myclass{ int *p; public: myclass(int i); ~myclass(){ delete p; } friend int getval(myclass o); }; myclass::myclass(int i) { p=new int; if(!p){ cout<< "allocation error\n"; exit(1); } *p=i; } int getval(myclass o) { return *o.p; } int main(int argc, char *argv[]) { myclass a(1),b(2); cout<<getval(a)<<" "<<getval(b); cout<<"\n"; cout<<getval(a)<<" "<<getval(b); system("pause"); return 0; } output: 1 2 0 4072544 =====================下面是增加一段copy constructor================ #include <cstdlib> #include <iostream> using namespace std; class myclass{ int *p; public: myclass(int i); myclass(const myclass &o); //copy constructor ~myclass(){ delete p; } friend int getval(myclass o); }; myclass::myclass(int i) { p=new int; if(!p){ cout<< "allocation error\n"; exit(1); } *p=i; } //copy construtor myclass::myclass(const myclass &o) { p=new int; if(!p){ cout<<"allocation error\n"; exit(1); } *p=*o.p; } int getval(myclass o) { return *o.p; } int main(int argc, char *argv[]) { myclass a(1),b(2); cout<<getval(a)<<" "<<getval(b); cout<<"\n"; cout<<getval(a)<<" "<<getval(b); system("pause"); return 0; } output: 1 2 1 2 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.116.133.98

03/16 22:53, , 1F
還在加班跟蟲蟲大軍奮戰 囧 先給方向:Effective C++ 的
03/16 22:53, 1F

03/16 22:53, , 2F
Item 11
03/16 22:53, 2F

03/16 23:02, , 3F
啊,抱歉,在 3rd Edition 應該是 Item 14
03/16 23:02, 3F

03/16 23:06, , 4F
找機會再來借這本書...XD thanks!
03/16 23:06, 4F
文章代碼(AID): #19lcPTq8 (C_and_CPP)
討論串 (同標題文章)
文章代碼(AID): #19lcPTq8 (C_and_CPP)