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;
        }
        friend Complex operator + (Complex &c1, Complex &c2); //宣告過載運算子
        void display();

    private:
        double real;
        double imag;
};

Complex operator +(Complex &c1,Complex &c2)
{
    return Complex(c1.real + c2.real, c1.imag + c2.imag);
}

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;
}

此主函式中執行c3 = c1 + c2呼叫了過載運算子operator +;

並且此過載運算子函式是Complex的友元函式。

必須是Complex物件相加才可以。

執行結果: