在 C++ 中使用它
usage of this in c++
本文关键字:C++ 更新时间:2023-10-16
我是 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
?
有人请帮帮我,谢谢。
简单的答案是this
是一个指针,所以要取消引用它,你需要使用 ->
而不是 .
。
将此视为替代实现:
add add::operator +(add z)
{
z.a += a;
z.b += b;
return z;
}
你按值传入z
(即副本),所以你不需要再做一个副本作为temp
,你可以简单地改变这个副本并按值返回它。
如果你实现+=
,你的实现可能看起来像这样,通过常量引用传入z
,但更新(并返回)this
,正如另一个答案所说,这是一个指针。并不是说您不必显式取消引用this
来修改类的成员:
add& add::operator +=(add const& z)
{
a += z.a;
b += z.b;
return *this;
}
成员函数通过名为 this
的额外隐式参数访问调用它们的对象。当我们调用成员函数时,this
使用调用该函数的对象地址进行初始化。
编译器将对象的地址传递给成员函数中的隐式this
参数。
由于this
是指针,因此请使用->
运算符。
相关文章:
- 没有找到相关文章