C++运算符重载

//运算符重载
//不能重载的运算符  ::  . .* ?: sizeof
//
#include<iostream>
using namespace std;
class Complex
{   
    friend ostream& operator<<(ostream& out, Complex c);
    friend Complex operator+(const Complex& c1, const Complex& c2);
    friend Complex operator-(const Complex& c2);
    double m_real;
    double m_vir;
public:
    Complex(double real = 0, double vir = 0) :m_real(real), m_vir(vir) {}
    void print()
    {
        cout << m_real << "+" << m_vir << "i" << endl;
    }
    Complex operator-(const Complex& c2)
    {
        cout << "成员重载" << endl;
        Complex temp;
        temp.m_real = this->m_real - c2.m_real;
        temp.m_vir = this->m_vir - c2.m_vir;
        return temp;
    }
    Complex& operator++(int)
    {
        this->m_real++;
        this->m_vir++;
        return *this;
    }
    //重载后++
    Complex operator++()
    {
        Complex c = *this;
        this->m_real++;
        this->m_vir++;
        return c;
    }
};
Complex operator+(const Complex& c1, const Complex& c2)
{
    cout << "外面的" << endl;
    Complex temp;
    temp.m_real = c1.m_real + c2.m_real;
    temp.m_vir = c1.m_vir + c2.m_vir;
    return temp;
}
ostream& operator<<(ostream& out, Complex c)
{
    out << c.m_real<<" +" << c.m_vir<<"i";
    return out;
}
int main()
{
    Complex cp1(1, 2);
    Complex cp2(3, 4);
    Complex cp3;
    //双目 用友元重载 左操作数做第一参数 右操作数做第二参数
    cp3 = cp1 + cp2;//cp3=operator+(cp1,cp2)
    cp3.print();
    //cp3 = cp2 - cp1;
    cp3 = cp2.operator-(cp1);
    cp3.print();
    cout << "-------------------------------" << endl;
    //单目 ++ --
    //单目用友元  只有一个参数 操作数就是参数
    //用成员函数  没有参数(有一个隐藏this)
    cout << ++cp3 << endl;
    cout << cp3++ << endl;
    cout << cp3 << endl;
    return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值