我有一个类,其成员如下
CRectangle CRectangle::operator+ (CRectangle param) {
CRectangle temp;
temp.width = new int;
temp.height = new int;
*temp.width = *width + *param.width;
*temp.height = *height + *param.height;
return (temp);
}
CRectangle& CRectangle::operator= (CRectangle param) {
*width = *param.width;
*height = *param.height;
return *this;
}
CRectangle::~CRectangle () {
n--;
delete width;
delete height;
}
现在如果我这样做
CRectangle a(3, 4), b(5, 6), c;
cout << b.area() << endl; // gives 30
c = a + b;
cout << b.area() << endl; // gives random value
然后对象 b
也会调用析构函数。我的意思是,它应该在 temp 上调用,但为什么在 b
上调用?
这与我传递参数的方式有关吗?
最佳答案
因为您没有将常量引用传递给运算符函数(您应该传递)。该函数也应该是 const
:
CRectangle CRectangle::operator+ (const CRectangle ¶m) const {...}
关于c++ - 在 C++ 中的 operator= 之后调用的析构函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20175573/