c++ - 在 C++ 中的 operator= 之后调用的析构函数

标签 c++ operator-overloading destructor

我有一个类,其成员如下

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 &param) const {...}

关于c++ - 在 C++ 中的 operator= 之后调用的析构函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20175573/

相关文章:

c++ - 在 CLion 中将 SDL2 与 CMake 结合使用

c++ - 字符串作为参数 (C++)

c++ - c++构造对象时圆括号和大括号有什么区别

c++ - "operator/"的分母

c++ - 有没有办法将所有赋值运算符(+=、*= 等)转发为隐式使用重写的直接赋值运算符 (=)?

c++ - 过渡到使用 noexcept 隐式声明析构函数的 C++11

c++ - 从子析构函数中删除父构造函数所做的分配

c++ - 从 C 头文件生成 MS Word 表

c++ - g++ 编译器为表达式提供 << 类型错误,但在 Visual Studio 中有效

c++ - 未定义对 C++ 中析构函数错误的引用?