重载双目操作符解决方案
如果是重载双目操作符(即为类的成员函数),就只要设置一个参数作为右侧运算量,而左侧运算量就是对象本身。
note:C++规定操作符重载默认为全局性质的,即使定义在类内部,也不能访问类的私有成员,只能定义为友元函数或者通过其他方式访问私有成员。
流操作符:<< >>,将类内部的私有成员进行输入输出
- 使用常规成员函数
对于>>或者<<,左侧运算量是cin或者cout,不是对象本身,如果一定要声明为常规成员函数(通过this指针访问本类的成员,可以少写一个参数,但是表达式左边的第一个参数必须是类对象,通过该类来调用成员函数),只能如下:
可以省略一个参数,但是调用时只能data<<cout;不符合习惯#include <iostream> using namespace std; class complex { public: complex(int x, int y) : real(x), imag(y) {} complex() :complex(0, 0) {} ~complex() {} ostream& operator << (ostream& cout); private: int real; int imag; }; ostream& complex:: operator << (ostream& cout) { cout << this->real << "+" << this->imag << "i" << endl; return cout; } //调用 int main() { complex data(1, 2); data << cout;//不符合习惯 return 0; }
- 常规操作,利用友元函数重载流操作符,友元函数一定程度破坏了封装性
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; }
-
定义在类外部,使用类的成员函数暴露对类成员的访问(推荐方案,增加封装性)
#include <iostream> using namespace std; 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); ostream& operator << (ostream& cout, complex& par) { cout << par.getReal() << " + " << par.getImag() << "i" << endl; return cout; } //调用 int main() { complex data(1, 2); cout<<data; return 0; }