11.5.1重学C++之【加号运算符重载】

#include<stdlib.h>
#include<iostream>
#include<string>
using namespace std;


/*
   4.5 运算符重载
        对已有运算符重新进行定义,赋予其另一种功能,以适应不同的数据类型

    4.5.1 加号运算符重载
        实现两个自定义数据类型相加的运算
        实现方式两种
            成员函数重载+
            全局函数重载+

    总结:
        对于内置数据类型的表达式的运算符是不可能改变的,例如1+1=2,你的重载不允许=0(1-1)
        不要滥用运算符重载
*/


class Person{
public:
    int a;
    int b;

    /*
    // 1 成员函数重载+
    Person operator+(Person & p){
        Person temp;
        temp.a = this->a + p.a;
        temp.b = this->b + p.b;
        return temp;
    }
    */
};


// 2-1 全局函数重载+ -- 正常版本
Person operator+(Person & p1, Person & p2){
    Person temp;
    temp.a = p1.a + p2.a;
    temp.b = p1.b + p2.b;
    return temp;
}


// 2-2 全局函数重载+ -- 函数重载版本
Person operator+(Person & p1, int num){
    Person temp;
    temp.a = p1.a + num;
    temp.b = p1.b + num;
    return temp;
}


void test1(){
    Person p1;
    p1.a = 10;
    p1.b = 10;

    Person p2;
    p2.a = 10;
    p2.b = 10;

    // 成员函数重载+本质调用
    //Person p3 = p1.operator+(p2); // 效果同Person p3 = p1 + p2;

    // 全局函数重载+本质调用
    //Person p3 = operator+(p1, p2); // 效果同Person p3 = p1 + p2;

    Person p3 = p1 + p2; // 正常相加报错,实现重载+(两种方式均可)后可运行
    cout << p3.a << endl;
    cout << p3.b << endl;

    // 运算符重载,也可以函数重载
    Person p4 = p3 + 100; // Person + int
    cout << p4.a << endl;
    cout << p4.b << endl;
}


int main()
{
    test1();

    system("pause");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/HAIFEI666/article/details/114891757