class 指针的运算符重载无法正常工作
Operator overloading not working as intended for class pointers
我编写了一个非常简单的程序来尝试理解 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;
}
会给你预期的结果。
我编写了一个非常简单的程序来尝试理解 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;
}
会给你预期的结果。