// 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;
}