插入運算符“

介紹

在C++語言提供的I/O系統中,運算符“<<”的重載函數被定義爲輸出流類ostream的成員函數,分別對char、int、long、float、double、字符串、指針等基本類型進行了重載。

對於我們自己定義的類,我們也可以對類的輸出重載運算符“<<”。這樣就可以直接輸出類對象啦。

技術要點

1.使用了友元函數,詳見友元函數與運算符重載的結合

2.使用了引用型的函數返回值,詳見引用型的函數返回值

示例代碼


#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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章