011. C++ friend使用(待整理)

1.friend 友元

  • 将一个函数定义为friend,可以读取private数据;
  • 显然,friend提供便利的同时,会破坏C++的封装性,因此,建议谨慎使用,朋友多了也许是个困扰。
class complex
{
public:
    complex(double r = 0, double i = 0)
        : re(r), im(i)
    {}
    complex& operator += (const complex&);
    double real() const { return re; }
    double imag() const { return im; }

private:
    double re;
    double im;

    friend complex& __doapl(complex*, const complex&);
};
inline complex&
__doapl(complex* ths, const complex* r)
{
    ths->re += r.re;  //自由取得friend的private成员
    ths->im += r.im;
    return *ths; 
}

2.相同class的各个objects互为friends

class complex
{
public:
    complex(double r = 0, double i = 0)
        : re(r), im(i)
    {}
    
    int func(const complex& param)
    {
        return param.re + param.im;
    }

private:
    double re,im;
};

{
    complex c1(2, 1);
    complex c2;
    c2.func(c1);
}

猜你喜欢

转载自www.cnblogs.com/paulprayer/p/10155037.html