1. 程式人生 > >運算子過載 加減乘除

運算子過載 加減乘除

#include <iostream>
using namespace std;//運算子的過載
class A
{
public:
    A(int x)
    {
        a = x;
    }
    ~A()
    {

    }
    //運算子過載函式+=;加法
    A operator +=(const A&b)
    {
        this->a = this->a+ b.a;
        return this->a;
    }

    A operator -=(const A&b)
    {
    //運算子過載函式-=;減法
        this->a = this->a- b.a;
        return this->a;
    }

    A operator *=(const A&b)
    {
    //運算子過載函式*=;乘法
        this->a = this->a* b.a;
        return this->a;
    }
    A operator /=(const A&b)
    {
    //運算子過載函式/=;除法
        this->a = this->a/ b.a;
        return this->a;
    }
    int a;
};
void main()
{
    A a(1);
    A b(2);
    A c(3);
    A d(4);
    A e(5);
    b += a;//現在才可以編譯通過,進行加減乘除運算
    c -= a;
    d *= a;
    e /= a;
    cout<<"運算子過載加法結果是:"<<b.a<<endl;
    cout<<"運算子過載減法結果是:"<<c.a<<endl;
    cout<<"運算子過載乘法結果是:"<<d.a<<endl;
    cout<<"運算子過載除法結果是:"<<e.a<<endl;
}

使用過載函式:

    A operator +=(const A&b)
    {
        this->a = this->a+ b.a;
        return this->a;
    }