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