C++ 流操作符重载函数
生活随笔
收集整理的這篇文章主要介紹了
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++ 流操作符重载函数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Vue学习笔记(5)(Vuex)
- 下一篇: 数据产品-数据分析方法论和分析方法介绍