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

歡迎訪問 生活随笔!

生活随笔

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

c/c++

C++ 流操作符重载函数

發布時間:2025/3/17 c/c++ 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 C++ 流操作符重载函数 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

1. 問題

  在C++中,在進行輸入輸出操作時,我們首先會想到用cout, cin這兩個庫操作語句來實現,比如

    cout << 8 << "hello world!" << endl;

    cin >> s;

  cout,cin分別是庫ostream, istream里的類對象

  如果想要cout,cin來輸出或輸入一個類對象,這樣的需求它能滿足嗎?很顯然,原來的cout不太可能滿足直接輸入輸出一個我們自定義的類對象,

  但是只要我們對<<, >>操作符進行重載就可以讓它處理自定義的類對象了。

2. 實現

  有一復數類:

class Complex {priate:int real;int imag;public:Complex(int r=0, int i=0):real(r),imag(i) {cout << real << " + " << imag << "i" ;cout << "complex class constructed."} }

int main() {
? ? ? Complex c; // output : 0+0i, complex class constructed.
? ? ? cout << c ; // error

? ? ? return 0;
}

  之所以上面main函數中 cout << c會出錯,是因為 cout本身不支持類對象的處理,如果要讓它同樣能打印類對象,必須得重載操作符<<.

#include <iostream> #include <string>class Complex {priate:int real;int imag;public:Complex(int r=0, int i=0):real(r),imag(i) {cout << real << " + " << imag << "i" ;cout << "complex class constructed."} // overload global functionfriend ostream & operator<<(ostream & o, const Complex & c);friend istream & operator >> (istream & i, Complex & c); }ostream & operator<<(ostream & o, const Complex & c) {o<< c.real << "+" << c.imag << "i";return o; }istream & operator >> (istream & i, Complex & c){string s;i >> s; // simillar to cin >> s; input string format like as a+bi... // parse s and get the real and imagc. real = real;c.imag = imag;return i; }

  重載了操作符 <<, >> 運算后, 就可以對類Complex直接進行 輸入輸出操作了,比如

int main{Complex c, c1;cin >> c; //input : 3+4icout << c <<";" << c1 << " complex output."; // output : 3+4i; 0+0i complex output. }

?

轉載于:https://www.cnblogs.com/lovemo1314/p/4069600.html

總結

以上是生活随笔為你收集整理的C++ 流操作符重载函数的全部內容,希望文章能夠幫你解決所遇到的問題。

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