介绍
在C++语言提供的I/O系统中,运算符“<<”的重载函数被定义为输出流类ostream的成员函数,分别对char、int、long、float、double、字符串、指针等基本类型进行了重载。
对于我们自己定义的类,我们也可以对类的输出重载运算符“<<”。这样就可以直接输出类对象啦。
技术要点
示例代码
#include<iostream>
using namespace std;
class Complex{
int real;
int imaginary;
public:
Complex(int r, int i) :real(r), imaginary(i){};
friend ostream & operator << (ostream &output, Complex complex){
output << complex.real << " + " << complex.imaginary << "i";
return output;
}
};
void main(){
Complex a(2, 3), b(5, 6);
cout << a << endl << b << endl;
}