Re: [問題] 問一個物件相加 operator+ 的問題....

看板C_and_CPP (C/C++)作者 (CA)時間16年前 (2009/05/15 15:09), 編輯推噓0(001)
留言1則, 1人參與, 最新討論串4/4 (看更多)
※ 引述《aquatear (米蟲)》之銘言: : ※ 引述《aquatear (米蟲)》之銘言: : : CWin operator+(CWin &w) : : { : : int width,height; : : width = this->width > w.width ? this->width: w.width; : : height = this->height > w.height ? this->height : w.height; : : return CWin(100,width,height,"new win"); : : } : CWin& operator=(CWin &w) : { : width = w.width; : height = w.height; : delete [] this->title; : this->title = new char[strlen(w.title)+1]; : strcpy(this->title,w.title); : return *this; : } 你兩個函式都有一個重大缺點,就是沒有適當的 const 修飾 這會造成 const 物件無法使用 + 和 = 另外 operator = 記得要做證同測試 if( *this == &w ) { return *this; } 否則在 a = a; 時有機會掛掉 說到底,如果你的 title 是 std::string 根本就不需要這麼麻煩 -- 自High筆記(半荒廢) http://legnaleurc.blogspot.com/ -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 122.146.203.213

05/17 06:39, , 1F
:( 不喜歡限制人家用甚麼 想用*就爽快的用!
05/17 06:39, 1F
文章代碼(AID): #1A3HKYQF (C_and_CPP)
文章代碼(AID): #1A3HKYQF (C_and_CPP)