设为首页 加入收藏

TOP

C++运算符重载为友元函数学习笔记
2015-07-24 05:41:30 来源: 作者: 【 】 浏览:5
Tags:运算 重载 函数 学习 笔记

初探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);
};



】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇HDOJ1166 敌兵布阵 [线段树] 下一篇hdu3666 THE MATRIX PROBLEM --- ..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: