C++重载>>和<<输入和输出运算符)
生活随笔
收集整理的這篇文章主要介紹了
C++重载>>和<<输入和输出运算符)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
在C++中,標(biāo)準(zhǔn)庫本身已經(jīng)對(duì)左移運(yùn)算符<<和右移運(yùn)算符>>分別進(jìn)行了重載,使其能夠用于不同數(shù)據(jù)的輸入輸出,但是輸入輸出的對(duì)象只能是 C++ 內(nèi)置的數(shù)據(jù)類型(例如 bool、int、double 等)和標(biāo)準(zhǔn)庫所包含的類類型(例如 string、complex、ofstream、ifstream 等)。
如果我們自己定義了一種新的數(shù)據(jù)類型,需要用輸入輸出運(yùn)算符去處理,那么就必須對(duì)它們進(jìn)行重載。本節(jié)以前面的 complex 類為例來演示輸入輸出運(yùn)算符的重載。
其實(shí) C++ 標(biāo)準(zhǔn)庫已經(jīng)提供了 complex 類,能夠很好地支持復(fù)數(shù)運(yùn)算,但是這里我們又自己定義了一個(gè) complex 類,這樣做僅僅是為了教學(xué)演示。
本節(jié)要達(dá)到的目標(biāo)是讓復(fù)數(shù)的輸入輸出和 int、float 等基本類型一樣簡單。假設(shè) num1、num2 是復(fù)數(shù),那么輸出形式就是:
#include <iostream> using namespace std; class complex { public:complex();complex(double a);complex(double a, double b);friend complex operator+(const complex & A, const complex & B);friend complex operator-(const complex & A, const complex & B);friend complex operator*(const complex & A, const complex & B);friend complex operator/(const complex & A, const complex & B);friend istream &operator>>(istream & in ,complex & A);friend ostream &operator<<(ostream & out ,complex & A);void display()const; private:double real; //復(fù)數(shù)的實(shí)部double imag; //復(fù)數(shù)的虛部 }; complex::complex() {real = 0.0;imag = 0.0; } complex::complex(double a) {real = a;imag = 0.0; } complex::complex(double a, double b) {real = a;imag = b; } //打印復(fù)數(shù) void complex::display()const {cout<<real<<" + "<<imag<<" i "; } //重載加法操作符 complex operator+(const complex & A, const complex &B) {complex C;C.real = A.real + B.real;C.imag = A.imag + B.imag;return C; } //重載減法操作符 complex operator-(const complex & A, const complex &B) {complex C;C.real = A.real - B.real;C.imag = A.imag - B.imag;return C; } //重載乘法操作符 complex operator*(const complex & A, const complex &B) {complex C;C.real = A.real * B.real - A.imag * B.imag;C.imag = A.imag * B.real + A.real * B.imag;return C; } //重載除法操作符 complex operator/(const complex & A, const complex & B) {complex C;double square = B.real * B.real + B.imag * B.imag;C.real = (A.real * B.real + A.imag * B.imag)/square;C.imag = (A.imag * B.real - A.real * B.imag)/square;return C; }//重載輸入操作符 istream & operator>>(istream & in ,complex & A) {in >>A.real>>A.imag;return in ; }//重載輸出操作符 ostream & operator<<(ostream &out ,complex &A) {out <<A.real<<"+"<<A.imag<<" i ";return out ; }int main() {complex c1(3, 4);complex c2(1, 2);complex c3;c3 = c1 + c2;cout<<"c1 + c2 = "<<c3<<endl;//c3.display();//cout<<endl;c3 = c1 - c2;cout<<"c1 - c2 = "<<c3<<endl;//c3.display();//cout<<endl;c3 = c1 * c2;cout<<"c1 * c2 = "<<c3<<endl;//c3.display();//cout<<endl;c3 = c1 / c2;cout<<"c1 / c2 = "<<c3<<endl;//c3.display();//cout<<endl;return 0; } c1 + c2 = 4+6 i c1 - c2 = 2+2 i c1 * c2 = -5+10 i c1 / c2 = 2.2+-0.4 i總結(jié)
以上是生活随笔為你收集整理的C++重载>>和<<输入和输出运算符)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++用顶层函数重载操作符(三)用友元优
- 下一篇: 超过1000本的计算机经典书籍分享