在c ++中使用它

sta*_*k92 0 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;
}
Run Code Online (Sandbox Code Playgroud)

这个程序现在工作正常.但是,我早些时候写过

temp.a=this.a+z.a;
temp.b=this.b+z.b;
Run Code Online (Sandbox Code Playgroud)

考虑到调用与编译时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’
Run Code Online (Sandbox Code Playgroud)

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

有人请帮帮我.谢谢.

Jon*_*ter 9

简单的答案是它this是一个指针,所以要取消引用它你需要使用->而不是..