Re: [問題] 問一個物件相加 operator+ 的問題....
※ 引述《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
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 4 之 4 篇):
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章