我想重载C++中的运算符。为目的,我写以下代码:返回这个或* this在运算符重载?
#include <iostream>
using namespace std;
class Box
{
public:
int height;
int width;
int length;
public:
Box operator+(const Box& b)
{
this->length = this->length + b.length;
this->width = this->width + b.width;
this->height = this->height + b.height;
return *this;
}
};
int main()
{
Box b1,b2;
b1.length = 5;
b1.width = 5;
b1.height = 5;
cout << "Length is : " << b1.length;
cout << "width is : " << b1.width;
cout << "height is : " << b1.height;
b2.length = 5;
b2.width = 5;
b2.height = 5;
b1 = b1 + b2 ;
cout << "Length is : " << b1.length;
cout << "width is : " << b1.width;
cout << "height is : " << b1.height;
cout << "Hello from first c++";
return 0;
}
的主要部分是:
Box operator+(const Box& b)
{
this->length = this->length + b.length;
this->width = this->width + b.width;
this->height = this->height + b.height;
return *this;
}
我无法理解:
这 - >长度=此 - >长度+ b.length;
return * this;
this.length在这里不起作用。 我为什么要return *this
? return this
在这里还不够吗?
你不是真的想要二元运算符+来修改它的任何一个操作数。 – juanchopanza
http://stackoverflow.com/questions/4421706/operator-overloading检查了这一点。 – basav