c++ 加号运算符重载
时间: 2024-01-31 10:10:02 浏览: 130
以下是两种C++中加号运算符重载的例子:
1. 类内重载
```cpp
class Person {
public:
Person operator+(const Person& p) {
Person tmp;
tmp.age = this->age + p.age;
return tmp;
}
int age;
};
void test01() {
Person p1;
p1.age = 20;
Person p2(p1);
Person p3 = p1 + p2; // 或者写为 p3 = p1.operator+(p2)
cout << p3.age << endl;
}
int main() {
test01();
return 0;
}
```
2. 类外重载
```cpp
class Person {
public:
int age;
};
Person operator+(const Person& p1, const Person& p2) {
Person tmp;
tmp.age = p1.age + p2.age;
return tmp;
}
void test01() {
Person p1;
p1.age = 20;
Person p2(p1); Person p3 = p1 + p2; // 或者写为 Person p3 = operator+(p1, p2);
cout << p3.age << endl;
}
int main() {
test01();
return 0;
}
```
阅读全文