1.先来看看友元函数重载流操作符实例
class complex
{
public:
complex(int x, int y): real(x), imag(y){}
complex():complex(0,0){}
~complex(){}
friend ostream& operator << (ostream& cout, complex& par);
private:
int real;
int imag;
}
ostream& operator << (ostream& cout, complex& par);
{
cout << par.real << "+" << par.imag << "i" << endl;
return cout;
}
2. 再来看看成员函数重载操作符实例
class complex
{
public:
complex(int x, int y): real(x), imag(y){}
complex():complex(0,0){}
~complex(){}
complex operator + (complex par)
{
complex resault;
resault.real = real + par.real;
resault.imag = imag + par.imag;
return resault;
}
private:
int real;
int imag;
}
成员函数运行机理:
假如C1与C2d都为complex类,则,C1+C2被编译系统解释为C1.operator +(C2);
对比可以得到结论:
1. 实际上流操作符左侧必须为cin或cout,即istream或ostream类,不是我们所能修改的类;或者说因为流操作符具有方向性。
这导致我们不能使用成员函数重载,只能使用类外的普通函数重载。
2. 由于我们将类内部的私有成员进行输入和输出,所以重载函数必须有对内部成员访问的权限。
这导致我们不能使用普通的函数重载,只能使用友元函数重载。
3. 好的解决方案
但是使用友元函数会破坏类的封装性,因此好的解决方法是:
使用一些成员函数来暴露对类成员的访问,然后使用类外的普通函数重载来进行类成员的输入输出。
代码如下:
class complex
{
public:
complex(int x, int y): real(x), imag(y){}
complex():complex(0,0){}
~complex(){}
int getReal(){ return real;}
int getImag(){ return imag;}
void setReal(int parm){ real = parm;}
void setImag(int parm){ imag = parm;}
private:
int real;
int imag;
}
ostream& operator << (ostream& cout, complex& par);
{
cout << par.getReal() << " + " << par.getImag() << "i" << endl;
return cout;
}