二元操作符重定义 //对*this=this->add(secondvec2d)的理解

本文通过三个C++代码示例,详细解析了运算符重载中的+=操作,展示了不同实现方式对类实例的影响,包括直接修改当前对象、生成新对象而不改变原对象,以及将新对象赋值给另一个变量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include
#include
#include
#include
using namespace std;
class V{
public:
int x;
V()=default;
V(int a):x(a) {}
V operator+=(const V& a){
x+=a.x;
return(*this);
}
};
int main(){
V c(3);
c+=V(3);
cout<<c.x;
return 0;
}


#include
#include
#include
#include
using namespace std;
class V{
public:
int x;
V()=default;
V(int a):x(a) {}
V operator+=(const V& a){
return(this->add(a));
}
V add(const V& a){
return V(x+a.x);
}
};
int main(){
V c(3);
c+=V(3);
cout<<c.x;
return 0;
}


#include
#include
#include
#include
using namespace std;
class V{
public:
int x;
V()=default;
V(int a):x(a) {}
V operator+=(const V& a){
return(this->add(a));
}
V add(const V& a){
return V(x+a.x);
}
};
int main(){
V c(3);
V D (c+=V(3) );
cout<<D.x;
return 0;
}
由此得出 第1种是返回自己的,所以c得到更新 输出6
第二种是产生一个新类 c没有更新 输出3
第三种 产生一个新类并将新类赋值给D 输出6

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值