跳转至

加号运算符重载

约 80 个字 42 行代码 预计阅读时间 1 分钟

Note

重载加法运算符 + 返回的是 Person 类型的对象,而不是对象的引用。这意味着在 operator+ 函数中创建了一个新的 Person 对象,并将其返回给调用方。这样做是为了避免悬空引用和对象生命周期管理的问题。

代码

#include <iostream>
using namespace std;
class Person{
public:
    Person(){};
    Person(int a,int b){
        this->a = a;
        this->b = b;

    };
    Person operator+ (const Person & p) const{
        Person temp;
        temp.a = this->a + p.a;
        temp.b = this->b + p.b;
        return temp;
    }
public:
    int a,b;
};

Person operator+ (const Person & p , int val) {
    Person temp;
    temp.a = p.a + val;
    temp.b = p.b + val;
    return temp;
}

void test(){
    Person p1(10,10);
    Person p2(20,20);
    Person p3 = p2 + p1;
    Person p4 = p1 + 10;
    cout << " a = " << p3.a << " " << "b = " << p3.b << endl;
    cout << " a = " << p4.a << " " << "b = " << p4.b << endl;
}

int main()
{
    test();
    return 0;
}

颜色主题调整

评论区~

有用的话请给我个赞和 star => GitHub stars
快来跟我聊天~