介紹
在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;
}