// 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="http://img.blog.csdn.net/20150515143615848?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvemhhb3lhcWlhbjU1Mg==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />
【c++】cout重载能不能写成成员函数,若能,写出函数原型,若不能,说明原因
原文地址:http://blog.csdn.net/zhaoyaqian552/article/details/45744407