操作符重载不能按照类指针的预期工作



我编写了一个非常简单的程序,试图理解c++中的操作符重载。但是,正如您将看到的,即使操作符重载返回了适当的值,d3维度的结果也不会更新。

#include <iostream>
using namespace std;
class dimention{

protected:
int width, height;

public:

dimention(int w = 0, int h = 0){
width = w;
height = h;
}

int getWidth(){
return width;
}
int getHeight(){
return height;
}
dimention& operator = (const dimention &d){
dimention *temp = new dimention;
temp->height = d.height;
temp->width = d.width;
return *temp;
}

dimention& operator + (const dimention &d){

dimention *newDimention = new dimention;

newDimention->width = this->getWidth() + d.width;
newDimention->height = this->getHeight() + d.height;
return *newDimention;
}

};
int main(){

dimention *d1 = new dimention(5, 5);
dimention *d2 = new dimention(1, 1);
dimention *d3 = new dimention;
*d3 = *d1;
cout << d3->getHeight() << endl;
cout << d3->getWidth() << endl;
*d3 = *d1 + *d2;
cout << d3->getHeight() << endl;
cout << d3->getWidth() << endl;
return 0;
}

谢谢你的帮助。

我想你误解了方法对对象的操作方式。

考虑赋值操作符:
dimention& operator = (const dimention &d){
dimention *temp = new dimention;
temp->height = d.height;
temp->width = d.width;
return *temp;
}

您从未编辑被分配给的对象本身(this)。相反,您正在创建(并泄漏)一个新的temp对象并对其进行更改。该对象不是d3

正确的实现是:

dimention& operator = (const dimention &d){
this->height = d.height;
this->width = d.width;
return *this;
}

会给你预期的结果。

最新更新