About overloads of the input (CIN)/output (cout).
In the header file of C + + has #include <iostream>, actually contains cin/cout, specifically: ostream corresponds to cout, and IStream corresponds to CIN.
I first implement the cout overload
#include <iostream>using namespace Std;class oc{public:private:int cnt;public:oc (int cnt) {this- >cnt = CNT; } Friend ostream& operator << (ostream& ost, const oc& Oc);};o stream& operator << (ostream& ost, const oc& Oc) {ost << oc.cnt; return OST;} int main () {System ("color 5A"); OC OC (2); cout << OC; return 0;}
Operation Result:
650) this.width=650; "title=" 01.png "src=" https://s5.51cto.com/wyfs02/M00/96/6B/ Wkiom1khen3w9wygaaaxybbzmyc741.png-wh_500x0-wm_3-wmp_4-s_1796254330.png "alt=" Wkiom1khen3w9wygaaaxybbzmyc741.png-wh_50 "/>
Explain:
①: Parameter ostream& ost, const oc& Oc, and return ostream& are all using references to prevent the call copy construct
②: Can be returned using void, but cannot use continuous output << oc << XXX
③: The left operand must be a Ostream object, so this overload must be implemented outside of the class
CIN Overloads:
#include <iostream>using namespace std;class oc{private: int cnt;public: oc ( int cnt) { this->cnt = cnt; } Friend istream& operator >> (&NBSP;ISTREAM&&NBSP;IST&NBSP;,&NBSP;OC&&NBSP;OC); friend int main ();}; Istream& operator >> (&NBSP;ISTREAM&&NBSP;IST&NBSP;,&NBSP;OC&&NBSP;OC) { ist >> oc.cnt; if ( ist.fail () ) { cout << "fail value to Oc.cnt! " << endl; oc.cnt = 0; } return ist;} Int main () { system ("color 5a"); oc oc (2); cin >> oc; cout << "OC.CNT&NBSP;VALUE&NBSP;IS&NBSP;: "&NBSP;<<&NBSP;OC.CNT&NBSP;<<&NBSP;ENDL;&NBSP;&NBSP;&NBSP;&NBSP;RETURN&NBSP;0;}
①, I first enter the correct value such as 1, the result is as follows:
650) this.width=650; "title=" 02.png "src=" https://s2.51cto.com/wyfs02/M02/96/6B/ Wkiom1khfilsv2lhaaazkobw-qg580.png-wh_500x0-wm_3-wmp_4-s_1560399804.png "alt=" Wkiom1khfilsv2lhaaazkobw-qg580.png-wh_50 "/>
②, enter a string in the wrong value. The results are as follows:
650) this.width=650; "title=" 03.png "src=" https://s5.51cto.com/wyfs02/M00/96/6B/ Wkiom1khfqlgmarmaaa162yd6pi317.png-wh_500x0-wm_3-wmp_4-s_1771697362.png "alt=" Wkiom1khfqlgmarmaaa162yd6pi317.png-wh_50 "/>
Ist.fail () is used to detect if the input failed. The string cannot be assigned a value for int. So---
CIN, like cout, can only be implemented outside the class.
This article is from the "Better_power_wisdom" blog, make sure to keep this source http://aonaufly.blog.51cto.com/3554853/1927956
C + + operator overloading (ii)