1. 程式人生 > >C++ 過載運算子 運算子過載函式作為類成員函式 過載運算子+

C++ 過載運算子 運算子過載函式作為類成員函式 過載運算子+

用運算子過載函式作為類成員函式的方法過載運算子+

下面的例子來自於課本:

#include <iostream>
using namespace std;

class Complex
{
    public:
        Complex() //無參建構函式
        {
            real = 0;
            imag = 0;
        }
        Complex(double r, double i) //有參建構函式
        {
            real  = r;
            imag = i;
        }
        Complex operator + (Complex &c2); //宣告過載運算子
        void display(); //成員函式,對類中的變數進行輸出

    private:
        double real;
        double imag;
};

Complex Complex::operator +(Complex &c2)
{
    Complex C;
    C.real = real + c2.real;
    C.imag = imag + c2.imag;
    return C;
}

void Complex::display()
{
    cout<<"("<<real<<","<<imag<<"i)"<<endl; //輸出複數形式
}

int main()
{
    Complex c1(3,4), c2(5,-10), c3;
    c3 = c1 + c2; //運算子+ 用於複數運算

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

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

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

    return 0;
}

主函式中執行c1+c2語句,是呼叫了運算子過載函式operator +;

相當於c1.operator + ( );

執行結果為: