c++之+运算符的重载

比如我们想要进行对象相加:

#include<iostream>
using namespace std;

class Person {
public:
    int a;
    int b;
    //通过成员函数重载加号运算符
    Person operator+(Person& p) {
        Person tmp;
        tmp.a = this->a + p.a;
        cout << this->a<<p.a<<endl;
        tmp.b = this->b + p.b;
        cout << this->b << p.b<<endl;
        return tmp;
    }
};
//通过全局函数重载
Person operator+(Person &p1,Person &p2){
    Person tmp;
    tmp.a = p1.a+p2.a;
    tmp.b = p1.b+p2.b;
    return tmp;
}
void test() {
    Person p1;
    p1.a = 1;
    p1.b = 2;
    Person p2;
    p2.a = 3;
    p2.b = 4;
    Person p3;
    p3 = p1 + p2;
//p3=p1.operator+(p2);
//p3=operator+(p1,p2); cout
<< "p3的a=" << p3.a << endl; cout << "p3的b=" << p3.b << endl; } int main() { test(); system("pause"); return 0; }

输出:

需要注意的是运算符重载,也可以发生函数重载。

猜你喜欢

转载自www.cnblogs.com/xiximayou/p/12097222.html
今日推荐