c++_类的运算符重载

#include <iostream>
using namespace std;


class Test
{
public:
    int a;
    int b;
public:
    Test(int a=0, int b=0)
    {
        cout << "有参构造函数" << endl;
        this->a = a;
        this->b = b;
    }
    ~Test()
    {
        cout << "a=" << a;
        cout << "析构函数" << endl;
    }


    void prinT()
    {
        cout << "a=" << a << "b=" << b << endl;
    }

    Test operator+(Test &t2)//类函数实现+号重载
    {
        Test tmp(this->a + t2.a, this->b + t2.b);
        return tmp;
    }
    Test& operator++()//前置++的重置
    {
        cout << "调用前置++" << endl;
        this->a++;
        this->b++;
        return *this;
    }
    Test operator++(int)//后置++的重置,利用占位形参实现函数重载
    {
        cout << "调用后置++" << endl;
        Test tmp = *this;
        return tmp;
        this->a++;
        this->b++;

    }
};


Test operator+(Test &t1, Test &t2)//全局函数方法实现+号重载
{
    cout << "运算符重载" << endl;
    Test tmp(t1.a + t2.a, t1.b + t2.b);
    return tmp;
}

int main()
{
    Test t1(1, 2);
    Test t2(3, 4);
    Test t3 = t1 + t2;
    t3.prinT();

    system("pause");
    return 0;
}

当类成员被定义为私有的,可利用友元函数实现全局运算符重载

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值