日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

C++重载>>和<<输入和输出运算符)

發布時間:2025/4/5 c/c++ 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 C++重载>>和<<输入和输出运算符) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

在C++中,標準庫本身已經對左移運算符<<和右移運算符>>分別進行了重載,使其能夠用于不同數據的輸入輸出,但是輸入輸出的對象只能是 C++ 內置的數據類型(例如 bool、int、double 等)和標準庫所包含的類類型(例如 string、complex、ofstream、ifstream 等)。

如果我們自己定義了一種新的數據類型,需要用輸入輸出運算符去處理,那么就必須對它們進行重載。本節以前面的 complex 類為例來演示輸入輸出運算符的重載。

其實 C++ 標準庫已經提供了 complex 類,能夠很好地支持復數運算,但是這里我們又自己定義了一個 complex 類,這樣做僅僅是為了教學演示。

本節要達到的目標是讓復數的輸入輸出和 int、float 等基本類型一樣簡單。假設 num1、num2 是復數,那么輸出形式就是:

#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; //復數的實部double imag; //復數的虛部 }; 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; } //打印復數 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

總結

以上是生活随笔為你收集整理的C++重载>>和<<输入和输出运算符)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。