在c ++中使用它

时间:2013-10-05 09:06:31

标签: c++ operator-overloading

我是c ++的新手。

#include<cstdio>
#include<string>
using namespace std;


class add{

public :
int a,b;
add();
add(int ,int);
add operator+(add);

};

add::add():a(0),b(0){};
add::add(int x,int y):a(x),b(y){};
add add::operator+(add z)
{
        add temp;
        temp.a=a+z.a;
        temp.b=b+z.b;
        return temp;
}

int main()
{
        add har(2,5),nad(3,4);
        add total;
        total=har+nad;
        cout<< total.a << " "<<total.b;
return 0;
}

这个程序现在工作正常。但是,我之前写过

temp.a=this.a+z.a;
temp.b=this.b+z.b;

考虑到调用total=har+nad;total=har.operator+(nad);相同,并且在编译时,会显示错误。

operover1.cpp: In member function ‘add add::operator+(add)’:
operover1.cpp:22:14: error: request for member ‘a’ in ‘this’, which is of non-class type ‘add* const’
operover1.cpp:23:14: error: request for member ‘b’ in ‘this’, which is of non-class type ‘add* const’

为什么我们不能在这里使用this.a+z.a

有人请帮帮我。谢谢。

3 个答案:

答案 0 :(得分:9)

简单的答案是this是指针,因此要取消引用它,您需要使用->而不是.

答案 1 :(得分:0)

将此视为替代实施:

add add::operator +(add z)
{
    z.a += a;
    z.b += b;
    return z;
}

您通过值(副本)在中传递z,因此您无需再创建另一个副本{{1} },你可以简单地改变这个副本并按值返回

如果您实施temp,您的实现可能如下所示,通过 const-reference 传递+=,但更新(并返回)z,就像另一个答案所说的那样,一个指针。并非您不必明确取消引用this来修改类的成员:

this

答案 2 :(得分:0)

成员函数通过名为this的额外隐式参数访问调用它们的对象。当我们调用成员函数时,this 初始化,其中包含调用该函数的对象的地址。

编译器将对象的地址传递给成员函数中的隐式 this参数。

由于this是指针,因此您使用->运算符。