C++运算符重载(友元函数方式)
生活随笔
收集整理的這篇文章主要介紹了
C++运算符重载(友元函数方式)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
我們知道,C++中的運算符重載有兩種形式:①重載為類的成員函數(見C++運算符重載(成員函數方式)),②重載為類的友元函數。
當重載友元函數時,將沒有隱含的參數this指針。這樣,對雙目運算符,友元函數有2個參數,對單目運算符,友元函數有一個參數。但是,有些運行符不能重載為友元函數,它們是:=,(),[]和->。
重載為友元函數的運算符重載函數的定義格式如下:
friend 函數類型 operator 運算符(形參表) { 函數體; }
一、程序實例
//運算符重載:友元函數方式 #include <iostream.h>class complex //復數類 { public:complex(){ real = imag = 0;}complex(double r, double i){real = r;imag = i;}friend complex operator + (const complex &c1, const complex &c2); //相比于成員函數方式,友元函數前面加friend,形參多一個,去掉類域friend complex operator - (const complex &c1, const complex &c2); //成員函數方式有隱含參數,友元函數方式無隱含參數friend complex operator * (const complex &c1, const complex &c2);friend complex operator / (const complex &c1, const complex &c2);friend void print(const complex &c); //友元函數private:double real; //實部double imag; //虛部};complex operator + (const complex &c1, const complex &c2) {return complex(c1.real + c2.real, c1.imag + c2.imag); }complex operator - (const complex &c1, const complex &c2) {return complex(c1.real - c2.real, c1.imag - c2.imag); }complex operator * (const complex &c1, const complex &c2) {return complex(c1.real * c2.real - c1.imag * c2.imag, c1.real * c2.real + c1.imag * c2.imag); }complex operator / (const complex &c1, const complex &c2) {return complex( (c1.real * c2.real + c1.imag * c2. imag) / (c2.real * c2.real + c2.imag * c2.imag), (c1.imag * c2.real - c1.real * c2.imag) / (c2.real * c2.real + c2.imag * c2.imag) ); }void print(const complex &c) {if(c.imag < 0)cout<<c.real<<c.imag<<'i'<<endl;elsecout<<c.real<<'+'<<c.imag<<'i'<<endl; }int main() { complex c1(2.0, 3.5), c2(6.7, 9.8), c3;c3 = c1 + c2;cout<<"c1 + c2 = ";print(c3); //友元函數不是成員函數,只能采用普通函數調用方式,不能通過類的對象調用c3 = c1 - c2;cout<<"c1 - c2 = ";print(c3);c3 = c1 * c2;cout<<"c1 * c2 = ";print(c3);c3 = c1 / c2;cout<<"c1 / c2 = ";print(c3);return 0; }
二、程序運行結果
從運行結果上我們就可以看出來,無論是通過成員函數方式還是采用友元函數方式,其實現的功能都是一樣的,都是重載運算符,擴充其功能,使之能夠應用于用戶定義類型的計算中。
三、兩種重載方式(成員函數方式與友元函數方式)的比較
一般說來,單目運算符最好被重載為成員;對雙目運算符最好被重載為友元函數,雙目運算符重載為友元函數比重載為成員函數更方便此,但是,有的雙目運算符還是重載為成員函數為好,例如,賦值運算符。因為,它如果被重載為友元函數,將會出現與賦值語義不一致的地方。
總結
以上是生活随笔為你收集整理的C++运算符重载(友元函数方式)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++运算符重载(成员函数方式)
- 下一篇: 虚函数和作用域(C++ primer 第