C++运算符重载(友元函数方式)
我們知道,C++中的運(yùn)算符重載有兩種形式:①重載為類(lèi)的成員函數(shù)(見(jiàn)C++運(yùn)算符重載(成員函數(shù)方式)),②重載為類(lèi)的友元函數(shù)。
當(dāng)重載友元函數(shù)時(shí),將沒(méi)有隱含的參數(shù)this指針。這樣,對(duì)雙目運(yùn)算符,友元函數(shù)有2個(gè)參數(shù),對(duì)單目運(yùn)算符,友元函數(shù)有一個(gè)參數(shù)。但是,有些運(yùn)行符不能重載為友元函數(shù),它們是:=,(),[]和->。
重載為友元函數(shù)的運(yùn)算符重載函數(shù)的定義格式如下:
friend 函數(shù)類(lèi)型 operator 運(yùn)算符(形參表) { 函數(shù)體; }
一、程序?qū)嵗?/span>
//運(yùn)算符重載:友元函數(shù)方式 #include <iostream.h>class complex //復(fù)數(shù)類(lèi) { 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,形參多一個(gè),去掉類(lèi)域friend complex operator - (const complex &c1, const complex &c2); //成員函數(shù)方式有隱含參數(shù),友元函數(shù)方式無(wú)隱含參數(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; //實(shí)部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)用方式,不能通過(guò)類(lèi)的對(duì)象調(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; }
二、程序運(yùn)行結(jié)果
從運(yùn)行結(jié)果上我們就可以看出來(lái),無(wú)論是通過(guò)成員函數(shù)方式還是采用友元函數(shù)方式,其實(shí)現(xiàn)的功能都是一樣的,都是重載運(yùn)算符,擴(kuò)充其功能,使之能夠應(yīng)用于用戶(hù)定義類(lèi)型的計(jì)算中。
三、兩種重載方式(成員函數(shù)方式與友元函數(shù)方式)的比較
一般說(shuō)來(lái),單目運(yùn)算符最好被重載為成員;對(duì)雙目運(yùn)算符最好被重載為友元函數(shù),雙目運(yùn)算符重載為友元函數(shù)比重載為成員函數(shù)更方便此,但是,有的雙目運(yùn)算符還是重載為成員函數(shù)為好,例如,賦值運(yùn)算符。因?yàn)?#xff0c;它如果被重載為友元函數(shù),將會(huì)出現(xiàn)與賦值語(yǔ)義不一致的地方。
總結(jié)
以上是生活随笔為你收集整理的C++运算符重载(友元函数方式)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: C++运算符重载(成员函数方式)
- 下一篇: s3c2440移植MQTT