【c++】cout過載能不能寫成成員函式,若能,寫出函式原型,若不能,說明原因
阿新 • • 發佈:2019-02-15
// cout過載能不能寫成成員函式,若能,寫出函式原型,若不能,說明原因 #include <iostream> using namespace std; // cout做友元 class A; ostream& operator<<(ostream &out, const A &a); class A { friend ostream& operator<<(ostream &out, const A &a); public: A(int n = 0):m(n) {} private: int m; }; ostream& operator<<(ostream &out, const A &a) { out << a.m; return out; } int main() { A a; cout << a << endl; return 0; } // cout並不是不可以做成員函式,但是它的輸出形式並不符合大家的習慣,所以還是不要把它寫到成員函式裡比較好 #include <iostream> using namespace std; class A { public: A(int n = 0) :m(n) {} // cout做成員函式 ostream& operator<<(ostream &out) { out << m; return out; } private: int m; }; int main() { A a; //注意輸出格式 a << cout << endl; return 0; }
<img src="https://img-blog.csdn.net/20150515143615848?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvemhhb3lhcWlhbjU1Mg==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />