#include<iostream>
#include<cmath>
using namespace std;
class Num {
public:
Num(int a) {
this->a = a;
}
void print() {
cout << a << endl;
}
//也可以在内部提供一个+号操作符重载,但和全局+号重载如果调用方法一致,就只能存在一个
Num operator+(Num& other) {
return Num(this->a + other.a);
}
//重载 +=,+=是修改自身,不能返回新对象,所以要返回自身引用
Num& operator+=(Num& other) {
this->a += other.a;
return *this;
}
#if 0
friend Num operator+(Num& c1,Num& c2);
#endif
private:
int a;//数据
};
#if 0
//全局提供一个+号操作符重载
Num operator+(Num& c1, Num& c2) {
return Num(c1.a + c2.a);
}
#endif
int main(int argc,char* argv[]) {
Num c1(10);
Num c2(10);
Num c3 = c1 + c2;//20
c3.print();
c3 += c2 += c2;//40
c3.print();
}
9.重载操作符
最新推荐文章于 2023-08-10 15:07:21 发布