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 
posted @   luoganttcc  阅读(3)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示