2015-09-27 56 views
0

我想重载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; 
     } 

我无法理解:

  1. 这 - >长度=此 - >长度+ b.length;

  2. return * this;

this.length在这里不起作用。 我为什么要return *thisreturn this在这里还不够吗?

+1

你不是真的想要二元运算符+来修改它的任何一个操作数。 – juanchopanza

+0

http://stackoverflow.com/questions/4421706/operator-overloading检查了这一点。 – basav

回答

2

1) “这” 是一个指针 2) “this” 指针是保持当前的对象的存储器地址的常数指针

会员签名: 箱操作者+(常量盒& B)

“为什么我应该返回这个?返回这是不够的吗?

如果您返回“this”,那么您将返回一个指针Box *,并且您的成员签名与此不符。

因此,您需要按值返回,因此请取消引用并返回。

+1

或'Box'应该有非显式构造函数'Box(Box *)':) – Nevermore

+0

为什么this-> length?为什么不把this.length作为b.length? – learner

+1

@learner,'this'是一个**指针**。通过指针访问成员是由'operator - >'实现的。通过引用或值访问成员由'operator.'实现。 C++不是Java和C#。 – Nevermore

0

无论何时返回引用或副本,都希望返回*this,并且仅在返回指向类对象的指针(几乎不会)时才返回this

0

This”是指向Box类型的对象的指针。 您的返回类型是Box类型的具体对象。当您返回* this时,您将取消引用指针并返回对象的引用(Box &),然后您的编译器使用复制构造函数Box(const Box &)将其转换为新对象。

事实上,如果你写了b3 = b1 + b2,你会注意到修改b3不会进一步修改b1。 这涉及你的问题的信。

作为一个方面说明,尽管如此,您在定义操作员的方式上有点混乱。通常当你超载你的算术运算符时,你可以超载运算符+和运算符+ =

运算符+返回给定类型的新的具体对象,不应该修改操作数。它的典型特征是:

Box Box::operator+(const Box& R) const 

所以典型的方式来实现它是使两个操作数的一个副本,然后做的总和,并返回这个新对象。注意该函数被声明为常量

如果您想按照您想要的方式修改第一个操作数,可以使用+ =操作符。 此运算符具有不同的签名,并且假定您修改操作数,并且在此情况下它实际上会返回应该是对左操作数的引用的引用。因此,在这种情况下,你将有

Box& Box::operator+=(const Box& R) 

在这种情况下,你可以看到,因为你承担你要修改操作,在这种情况下,你应该返回的功能是不恒定的*这是一个参考你刚刚修改的对象。

Quick guide on operator overloading

1

(撇开事实,你operator+()改变的this值)返回*this的原因是为了让这样的表述:

Box a, b, c; 
// ... init the Boxes 
Box d = a + b + c; 

在这种情况下a+b需求的结果将其“送入”operator+以将c的值添加到其中。这是通过创建一个代表a+b的结果的新临时对象来完成的(在你的情况下 - 这是在operator+中以*this返回的结果)。

现在你应该看到,如果你要返回一个指针this那么就没有办法优雅写下a+b+ca+b结果将不再是一个参考,以便正确地呼吁operator+这人会写这样的东西丑:

(a+b).operator+(c) 

同样的道理也适用于上述表达式分配operator= - 你真的想引用不返回一个指向你的对象,给它。