读书人

关于友元的有关问题?

发布时间: 2012-03-03 15:33:03 作者: rapoo

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

}

读书人网 >C++

热点推荐