1. 程式人生 > >C++的流插入運算子“”的過載

C++的流插入運算子“”的過載

C++的流插入運算子“<<”和流提取運算子“>>”是C++在類庫中提供的,所有C++編譯系統都在類庫中提供輸入流類istream和輸出流類ostream。cin和cout分別是istream類和ostream類的物件。在類庫提供的標頭檔案中已經對“<<”和“>>”進行了過載,使之作為流插入運算子和流提取運算子,能用來輸出和輸入C++標準型別的資料。因此,凡是用“cout<<”和“cin>>”對標準型別資料進行輸入輸出的,都要用#include 把標頭檔案包含到本程式檔案中。

使用者自己定義的型別的資料,是不能直接用“<<”和“>>”來輸出和輸入的。如果想用它們輸出和輸入自己宣告的型別的資料,必須對它們過載。

對“<<”和“>>”過載的函式形式如下:
istream & operator >> (istream &, 自定義類 &);
ostream & operator << (ostream &, 自定義類 &);
即過載運算子“>>”的函式的第一個引數和函式的型別都必須是istream&型別,第二個引數是要進行輸入操作的類。過載“<<”的函式的第一個引數和函式的型別都必須是ostream&型別,第二個引數是要進行輸出操作的類。因此,只能將過載“>>”和“<<”的函式作為友元函式或普通的函式,而不能將它們定義為成員函式;

file:Complex.h

#pragma once
#include <iostream>
using namespace std;
class Complex
{
public:
    Complex(){real = 0; imag = 0;}
    Complex(double r, double i){ real = r; imag = i; }
    friend ostream &operator<<(ostream&, Complex&);
    friend istream &operator>>(istream&, Complex&);
    Complex operator
+(Complex&c2); private: double real; double imag; };

fiel:Complex.cpp

#include "stdafx.h"
#include "Complex.h"


ostream& operator<<(ostream&output, Complex&c)
{
    output << "(" << c.real << "+" << c.imag << "i)" << endl;
    return output;
}
istream& operator>>(istream&intput, Complex&c)
{
    cout << "input real part and imaginary part of complex number";
    intput >> c.real >> c.imag;
    return intput;
}
Complex Complex::operator+(Complex& c2)
{
    return Complex(real + c2.real, imag + c2.imag);
}
#include "stdafx.h"
#include "Complex.h"
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
    Complex c1, c2, c3;
    cin >> c1 >> c2;
    c3 = c1 + c2;
    cout << c3;
    system("pause");
    return 0;
}