初探C++运算符重载学习笔记<2> 重载为友元函数

初探C++运算符重载学习笔记 

 

在上面那篇博客中,写了将运算符重载为普通函数类的成员函数这两种情况。

 

以下的两种情况发生。则我们须要将运算符重载为类的友元函数

<1>成员函数不能满足要求

<2>普通函数又不能訪问类的私有成员时

 

 

举例说明:

class Complex{
    double real, imag;
    public:
    Complex(double r, double i):real(r), imag(i){ }; 
    Complex operator+(double r);   
};
    Complex Complex::operator+(double r){

    return Complex(real + r, imag); 
}

 

定义一个复数类。重载'+'运算符,经过重载之后

Complex c ;
c = c + 5;  //有定义,相当于 c = c.operator +(5);

 

可是假设出现5+c,则编译出问题。此时还须要重载普通函数。

Complex operator+ (double r, const Complex & c) {
    return Complex( c.real + r, c.imag);
}


能解释 5+c,可是普通函数无法訪问类的私有成员。

 

这时就须要重载为类的友元函数

class Complex {
    double real, imag;
    public:
    Complex( double r, double i):real(r),imag(i){ }; 
    Complex operator+( double r );
    friend Complex operator + (double r, const Complex & c);
};


 


 

 

 

原文地址:https://www.cnblogs.com/lxjshuju/p/7120285.html