新手,友元问题,谢谢了。

clari 2004-08-11 08:59:43
编译后为什么说不能访问私有变量?我用的是VC6。谢谢了
错误信息是:
--------------------Configuration: test - Win32 Debug--------------------
Compiling...
test.cpp
G:\test.cpp(22) : error C2248: 'num' : cannot access private member declared in class 'Rational'
G:\test.cpp(6) : see declaration of 'num'
G:\test.cpp(22) : error C2248: 'den' : cannot access private member declared in class 'Rational'
G:\test.cpp(6) : see declaration of 'den'
G:\test.cpp(27) : error C2248: 'num' : cannot access private member declared in class 'Rational'
G:\test.cpp(6) : see declaration of 'num'
G:\test.cpp(27) : error C2248: 'den' : cannot access private member declared in class 'Rational'
G:\.cpp(6) : see declaration of 'den'
Error executing cl.exe.

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

程序如下:

#include<iostream>
using namespace std;

class Rational {
private:
long num, den;
public:
Rational (long num, long denom);
friend istream& operator >> (istream istr, Rational& x);
friend ostream& operator << (ostream ostr, const Rational& x);
};

Rational::Rational(long p, long q):num(p),den(q) {
if (den == 0) {
cerr << "A zero denominator is invalid. " << endl;
exit(1);
}
}

istream& operator >> (istream& istr, Rational& x) {
char c = '/';
istr >> x.num >> c >> x.den;
return istr;
}

ostream& operator << (ostream& ostr, const Rational& x) {
ostr << x.num << '/' << x.den;
return ostr;
}

int main() {return 0;}
...全文
154 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
clari 2004-08-12
  • 打赏
  • 举报
回复
谢谢各位,那个&号是我的手误,没有打上去,即便参数传递对了,在VC6下还是同样的错误。我按照RookieStar大哥的第一条改了程序,在VC6下可以通过了!谢谢啦!

我还在RedHat 9上运行了STL版的程序,它对友元的支持就没有问题,完全支持新ANSI标准,看来VC6真的老了。嘻嘻。

我是不是应该换个VC的版本?VC.net好用吗?我没用过。
RookieStar 2004-08-11
  • 打赏
  • 举报
回复
1。不用任何STL组件,且把头文件改成.h版本的

2。把友元的实现放到类中和声明合二为一。

这是因为VC6对友元支持差的缘故,这样修改应能通过。
willko 2004-08-11
  • 打赏
  • 举报
回复
friend istream& operator >> (istream /*这里*/istr, Rational& x);
friend ostream& operator << (ostream /*这里*/ostr, const Rational& x);
形参少了引用 &
willko 2004-08-11
  • 打赏
  • 举报
回复
定义与实现的参数不一。

33,311

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 新手乐园
社区管理员
  • 新手乐园社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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