对输出操作符重载后对类进行输出

来源:百度知道 编辑:UC知道 时间:2024/06/15 15:31:07
#include<iostream>
using namespace std;

//
class A
{
private:
int x;

public:
A() : x(1)
{
}

friend ostream& operator << (ostream& out, const A &a)
{
//out << a.x;
//return out;
}
};

ostream& operator << (ostream& out, const A &a)
{
out << a.x;
return out;
} ;

int main()
{
A a;
cout<<a<<endl;
return 0;
}
大家好,这是我前几天提问过的题目,但是我现在想把友元函数弄到类的外面来进行定义,我想应该是可以的吧,但是我调试了很久还是有些错误,清高手指点下,多谢,
这个程序编译错误显示在重载函数的输出时不能对类A的私有成员进行访问,(out << a.x; );
另重载函数在类中定义时是可以的。

这个程序能运行啊,输出结果:1
有什么问题?
友元函数定义在类外面,要在类中声明吧.看看:
#include<iostream>
using namespace std;

//
class A
{
private:
int x;

public:
A() : x(1)
{
}

friend ostream& operator << (ostream& out, const A &a);

};

ostream& operator << (ostream& out, const A &a)
{
out << a.x;
return out;
} ;

int main()
{
A a;
cout<<a<<endl;
return 0;
}

friend ostream& operator << (ostream& out, const A &a)
{
//out << a.x;
//return out;
}
改成
friend ostream& operator << (ostream& out, const A &a);
//{
//out << a.x;
//return out;
//}