0

我是 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在这里使用?

有人请帮帮我。谢谢。

4

3 回答 3

9

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

于 2013-10-05T09:09:28.813 回答
0

将此视为替代实现:

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

z您按传递(副本),因此您不需要再制作另一个副本,因为temp您可以简单地改变这个副本并按返回它。

如果您正在实施+=,您的实施可能看起来像这样,通过zconst -reference传入,但更新(并返回)this,正如另一个答案所说,这是一个指针。并不是说您不必显式取消引用this来修改类的成员:

add& add::operator +=(add const& z)
{
    a += z.a;
    b += z.b;
    return *this;
}
于 2013-10-05T09:45:12.490 回答
0

成员函数通过一个名为 的额外隐式参数访问调用它们的对象this。当我们调用成员函数时, 使用调用该函数的对象的地址进行this初始化

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

因为this是指针,您使用->运算符。

于 2014-11-27T22:55:14.533 回答