首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

关于友元的有关问题?

2012-03-03 
关于友元的问题??#includeiostreamusingnamespacestdclassRational{public:Rational(intnumerator0,in

关于友元的问题??
#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>


那位给在下解释一下,不胜感激


[解决办法]
这是因为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()
{

}

热点排行