第四周 运算符重载
1.运算符重载的基本概念
2.赋值运算符的重载
3.运算符重载为友元函数
4.运算符重载实例:可变长数组类的实现
5.流插入运算符和流提取运算符的重载
6.类型转换运算符、自增自减运算符的重载
3.运算符重载为友元函数
一般情况下,将运算符重载为类的成员函数,是较好的选择。但有时,重载为成员函数不能满足使用要求,重载为普通函数,又不能访问类的私有成员,所以需要将运算符重载为友元。
例子:
class Complex
{
double real,imag;
public:
Complex( double r, double i):real(r),imag(i){ };
Complex operator+( double r );
};
Complex Complex::operator+( double r )
{
//能解释 c+5
return Complex(real + r,imag);
}
经过上述重载后:
Complex c ;
c = c + 5; // 有定义,相当于 c = c.operator +(5);
但是:
c = 5 + c; //编译出错 编译出错
所以,为了使得上述的表达式能成立,需要将 + 重载为普通函数。
Complex operator+ (double r,const Complex & c)
{
//能解释 5+c
return Complex( c.real + r, c.imag);
}
但是普通函数又不能访问私有成员,所以需要将已经将运算符 + 重载的普通全局函数再次重载为这个类的友元。
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);
};