C++用顶层函数重载操作符(三)用友元优化
生活随笔
收集整理的這篇文章主要介紹了
C++用顶层函数重载操作符(三)用友元优化
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
我們以頂層函數的形式進行操作符重載,但是因為無法直接訪問 complex 類中的私有成員,故而在類中增添了 getimag()、getreal()、setimag() 和 setreal() 函數以操作類中的私有成員變量,如此一來實現這些操作符重載函數看上去就有些復雜了,不是那么直觀。除了此種方法以外,我們還可以將 complex 類中的私有成員 real 和 imag 聲明為 public 屬性,但如此一來就有悖類的信息隱藏機制了。除了這兩種方法外,我們是否還有其它方法解決這個問題呢
答案是肯定的,還有一種方法,前面章節我們介紹過友元函數,如果我們將操作符重載函數這些頂層函數聲明為類的友元函數,那么就可以直接訪問類的私有成員變量了。
#include <iostream> using namespace std; class complex { public:complex();complex(double a);complex(double a, double b);friend complex operator+(const complex & A, const complex & B);friend complex operator-(const complex & A, const complex & B);friend complex operator*(const complex & A, const complex & B);friend complex operator/(const complex & A, const complex & B);void display()const; private:double real; //復數的實部double imag; //復數的虛部 }; complex::complex() {real = 0.0;imag = 0.0; } complex::complex(double a) {real = a;imag = 0.0; } complex::complex(double a, double b) {real = a;imag = b; } //打印復數 void complex::display()const {cout<<real<<" + "<<imag<<" i "; } //重載加法操作符 complex operator+(const complex & A, const complex &B) {complex C;C.real = A.real + B.real;C.imag = A.imag + B.imag;return C; } //重載減法操作符 complex operator-(const complex & A, const complex &B) {complex C;C.real = A.real - B.real;C.imag = A.imag - B.imag;return C; } //重載乘法操作符 complex operator*(const complex & A, const complex &B) {complex C;C.real = A.real * B.real - A.imag * B.imag;C.imag = A.imag * B.real + A.real * B.imag;return C; } //重載除法操作符 complex operator/(const complex & A, const complex & B) {complex C;double square = B.real * B.real + B.imag * B.imag;C.real = (A.real * B.real + A.imag * B.imag)/square;C.imag = (A.imag * B.real - A.real * B.imag)/square;return C; } int main() {complex c1(3, 4);complex c2(1, 2);complex c3;c3 = c1 + c2;cout<<"c1 + c2 = ";c3.display();cout<<endl;c3 = c1 - c2;cout<<"c1 - c2 = ";c3.display();cout<<endl;c3 = c1 * c2;cout<<"c1 * c2 = ";c3.display();cout<<endl;c3 = c1 / c2;cout<<"c1 / c2 = ";c3.display();cout<<endl;return 0; } c1 + c2 = 4 + 6 i c1 - c2 = 2 + 2 i c1 * c2 = -5 + 10 i c1 / c2 = 2.2 + -0.4 i總結
以上是生活随笔為你收集整理的C++用顶层函数重载操作符(三)用友元优化的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++用顶层函数重载操作符(一)
- 下一篇: C++重载>>和<<输入和输出运算符)