定义一个Complex类,为其定义构造函数,析构函数,试对下列几个运算符进行重载:++,=,!=,+,-,==,其中要求要有成员重载形式和友元重载形式,而且,++运算符要求实现先加和后加两种形式。

#include <iostream>

#include <cmath>

using namespace std;

class com

{

    public:

    com(){a = 0;}

    com(int x):a(x){};

    friend com operator + (com &c1, com &c2);

    friend com operator - (com &c1, com &c2);

    com operator ++();

    com operator ++(int);

    friend bool operator !=(com &c1, com &c2);

    friend bool operator ==(com &c1, com &c2);

    com operator = (com &c2);

    void display();

    ~com(){cout<<"析构函数"<<endl;}

    private:

    int a;

};

com operator + (com &c1, com &c2)

{

    com c;

    c.a = c1.a+c2.a;

    cout<<"c1+c2 = "<<c.a<<endl;

    return c;

}

com operator - (com &c1, com &c2)

{

    com c;

    c.a = c1.a-c2.a;

    cout<<"c1-c2 = "<<c.a<<endl;

    return c;

}

com com::operator ++()

{

    ++a;

    return *this;

}

com com::operator++(int)

{

    a++;

    return *this;

}

bool operator !=(com &c1, com &c2)

{

    if(c1.a!=c2.a)

    return 1;

    else

    return 0;

}

bool operator ==(com &c1, com  &c2)

{

    if(c1.a==c2.a)

    return 1;

    return 0;

}

com com :: operator = (com &c2)

{

   a = c2.a;

   return *this;

}

void com::display()

{

    cout<<a<<endl;

}

int main()

{

    com c1(5), c2(1);

    com c3 = c1+c2;

    com c4 = c1-c2;

    if(c1==c2)

    cout<<"c1==c2"<<endl;

    else if(c1!=c2)

    {

        cout<<"c1!=c2"<<endl;

        c1++;

        cout<<"c1++"<<endl;

        cout<<"c1 = ";c1.display();

        ++c1;

        cout<<"++c1"<<endl;

        cout<<"c1 = ";c1.display();

    }

    c2 = c1;

    cout<<"c2 = c1"<<endl;

    cout<<"c1 = ";c1.display();cout<<"c2 = ";c2.display();

    return 0;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值