关于友元的问题??

zhangjgbupt 2007-06-30 09:16:38
#include <iostream>
using namespace std;


class Rational
{
public:
Rational(int numerator = 0, int denominator = 1)
{
n=numerator;
d=denominator;
}
friend ostream& operator<<(ostream& s, const Rational& );

private:
int n, d;// 分子,分母

};

ostream& operator<<(ostream& s, const Rational& r)
{
s<< r.n << '/' << r.d;
return s;
}

void main()
{

}



以上程序编译出错
--------------------Configuration: test - Win32 Debug--------------------
Compiling...
test.cpp
E:\c++study\test\test.cpp(23) : error C2248: 'n' : cannot access private member declared in class 'Rational'
E:\c++study\test\test.cpp(17) : see declaration of 'n'
E:\c++study\test\test.cpp(23) : error C2248: 'd' : cannot access private member declared in class 'Rational'
E:\c++study\test\test.cpp(17) : see declaration of 'd'
Error executing cl.exe.

test.exe - 2 error(s), 0 warning(s)


友元不是可以直接访问类私有变量吗?
如果我把头文件改成如下就编译则没有问题,奇怪中!!!!
#include <iostream.h>




那位给在下解释一下,不胜感激
...全文
213 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
aping21 2007-07-01
  • 打赏
  • 举报
回复
不同的编译器,头文件形式有一点不同。我用的Microsoft Visual C++ 6.0也是用<iostream.h>来表示。
zhangjgbupt 2007-07-01
  • 打赏
  • 举报
回复
<iostream.h> 保留原始的类实现, <iostream> 新的用模板实现, ...


那新的标准库在vc6里怎么支持不够呀,大家现在都用什么编译器呀
Vitin 2007-07-01
  • 打赏
  • 举报
回复
或者在原来的代码中,用 using std::ostream 代替 using namespace std; 即可。

总之建议使用VS2003或VS2005。它们全面地支持了C++98标准。
Vitin 2007-07-01
  • 打赏
  • 举报
回复
这是因为VC6对C++98标准的支持不是很好,当开放std名字空间并使用oprerator<<操作符重载时,将无法同时对其使用friend,因为std名字空间对oprerator<<操作符重载做了某些限制。

解决的方法是不使用using namespace std;

可以这样写:

#include <iostream>
//using namespace std;


class Rational
{
public:
Rational(int numerator = 0, int denominator = 1)
{
n=numerator;
d=denominator;
}
friend std::ostream& operator<<(std::ostream& s, const Rational& );

private:
int n, d;// 分子,分母

};

std::ostream& operator<<(std::ostream& s, const Rational& r)
{
s<< r.n << '/' << r.d;
return s;
}

void main()
{

}
uwinb 2007-06-30
  • 打赏
  • 举报
回复
<iostream.h> 保留原始的类实现, <iostream> 新的用模板实现, ...
Minkey 2007-06-30
  • 打赏
  • 举报
回复
都说VC6.0对标准库支持不够,呵呵;
Devcpp编译成功~~
zhangjgbupt 2007-06-30
  • 打赏
  • 举报
回复
我用的是vc6,呵呵,难道是编译器的问题??
星羽 2007-06-30
  • 打赏
  • 举报
回复
2005 没问题
kei_lin 2007-06-30
  • 打赏
  • 举报
回复
我在..VC2003下可以.
LZ用的可能..2005..

64,651

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧