加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c++之+运算符的重载

发布时间:2020-12-16 09:06:19 所属栏目:百科 来源:网络整理
导读:比如我们想要进行对象相加: #includeiostream using namespace std; class Person { public : int a; b; // 通过成员函数重载加号运算符 Person operator +(Person p) { Person tmp; tmp.a = this -a + p.a; cout this -ap.a endl; tmp.b = this -b + p.b;

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

#include<iostream>
using namespace std;

class Person {
public:
    int a;
     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;
     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; } main() { test(); system(pause"); return 0; }

输出:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读