友元函數與運算符重載的結合

寫在前面

之前的文章闡述了友元函數和友元類運算符重載,當運算符重載需要調用原類的私有成員或保護成員時,需要將運算符函數聲明爲友元函數。

例子

#include<iostream>
using namespace std;
class Complex{// 複數類
    double real, imag;// 實部和虛部
public:
    Complex(){ real = imag = 0; };
    Complex(double r, double i){ real = r; imag = i; }
    friend Complex operator + (Complex, Complex);// 友元+運算符重載:兩複數相加
    friend Complex operator - (Complex, Complex);// 友元+運算符重載:兩複數相減
    friend void printComplex(Complex c);// 輸出複數
};
Complex operator + (Complex c1, Complex c2){
    Complex c;
    c.real = c1.real + c2.real;
    c.imag = c1.imag + c2.imag;
    return c;
}
Complex operator - (Complex c1, Complex c2){
    Complex c;
    c.real = c1.real - c2.real;
    c.imag = c1.imag - c2.imag;
    return c;
}
void printComplex(Complex c){
    cout << c.real << "+" << c.imag << "i";
}
int main()
{
    Complex c1(1, 2), c2(3, 4);
    cout << "c1: ";
    printComplex(c1);
    cout << endl;
    cout << "c2: ";
    printComplex(c2);
    cout << endl;
    cout << "c1+c2: ";
    printComplex(c1 + c2);
    cout << endl;
    cout << "c1-c2: ";
    printComplex(c1 - c2);
    cout << endl;
}

運行結果

c1: 1+2i
c2: 3+4i
c1+c2: 4+6i
c1-c2: -2+-2i
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章