新手,友元问题,谢谢了。
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;}