作者legnaleurc (CA)
看板C_and_CPP
标题Re: [问题] 问一个物件相加 operator+ 的问题....
时间Fri May 15 15:09:19 2009
※ 引述《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
1F:→ dove1706::( 不喜欢限制人家用甚麽 想用*就爽快的用! 05/17 06:39