作者aquatear (米虫)
看板C_and_CPP
标题Re: [问题] 问一个物件相加 operator+ 的问题....
时间Fri May 15 14:35:44 2009
※ 引述《aquatear (米虫)》之铭言:
: 写了一个重载 + 号 的函式 , 目的是将两个 CWin 物件相加,
: 此物件是一个视窗, 相加结果是取视窗最大的宽高当作新视窗的宽高,
: 然後把新视窗的 title 设为 "new win"
: 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");
: }
hi! 上篇有人告诉我需要重载 "=" 运算子, 我觉得不需要
因为我以为 win1 = win2+win3; 在做完 win2+win3 时, 即
做完 operator+ 後, 会立刻把 operator+ 里的 local 物件解构销毁
其实不是这样
事实上是
会做完 win1=win2+win3 整行叙述, 也就是做完 operator+ , operator=
才会呼叫解构将 operator+ 里的物件销毁
所以还是需要自己写 operator= , 将 title 复制给 win3
这样就没问题了, 不过我觉得我的 operator= 写得非常鸟
如下
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;
}
因为一开始建构就会有一个 default 字串所以必须先 delete 掉
再根据新的 "new win" 配记忆体并复制,
不晓得有没有更简洁的方法
感谢大家讨论提供盲点 !
有需要 source 我可以贴出所有 source 给大家研究
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 61.219.68.170