求助:是VC的问题还是我的问题

来源:百度知道 编辑:UC知道 时间:2024/06/17 05:43:54
下面是我写的一段代码:

class Complex
{
public:
Complex() { Re=Im=0; }
Complex(float r) { Re=r; Im=0; }
Complex(float r, float i) { Re=r; Im=i; }
friend ostream& operator <<(ostream& os, const Complex& ob);

private:
float Re;
float Im;

};

ostream& operator << (ostream& os,const Complex &ob)
{

os<<ob.Re<<'+'<<ob.Im<<'i';
return os;
}
为何VC老是提示:
error C2248: 'Re' : cannot access private member declared in class 'Complex';
error C2248: 'Im' : cannot access private member declared in class 'Complex';
明明已经声明了友元函数了,而且在gcc下是可以的。

听说是VC问题,在类里面定义的友元函数才能访问私有变量
--------------------------------------
我记得以前候捷就曾经总结过各大编译器实现跟标准c++的区别,并写成了一篇文章

vc下的友元函数只能访问私有或保护变量.
你的代码把<<写成友元根本没意义.
因为你访问的是Complex,而不是在友元里访问Re和Im.
像你这样写要声明友元类才行.
所以还是加两个GetRe和GetIm吧.

我在VC6.0下编译运行都没问题。楼主友元用法没错。
不过如果使用如下语句却会出现,恐怕还是vc 一个bug哦
using namespace std;

如果用下述语句却不会错
using std::ostream;
using std::cout;
using std::endl;

这段代码在vc下不可能出错。

其它的问题