急求一有关友元的问题

来源:百度知道 编辑:UC知道 时间:2024/05/26 20:08:22
#include<iostream>
using namespace std;
class get_in
{
private:
int i;
public:
friend istream& operator>>(istream&, get_in&);
get_in(istream& is)
{
is >> *this;
}
get_in()
{
i = 0;
};
};
istream& operator>>(istream& in, get_in& b)
{
in >> b.i;
return in;
}
void main()
{
get_in a(cin);
}
以上是本人做的一个程序。可是在调试的过程中却出现了变量i是私有的不能访问的问题。二对于>>的重载我已经设置为友元了,于是十分费解,希望有能人能帮我解答一下。谢谢了!
注:由于本人就要期末考了,呵呵...希望可以尽快得到答案!再次感谢了!

其实这个程序,基本上是没有问题的。
之所以提示无法访问私有变量i,可以说是VC对C++支持的不好的缘故

修改方法有如下两种:
1、先声明一下那个友元函数
2、用#include<iostream.h>代替#include<iostream>和using namespace std;

//#include<iostream.h> //2、用#include<iostream.h>代替下面两句
#include<iostream>
using namespace std;

//1、先声明一下友元函数
class get_in ;
istream& operator>>(istream& in, get_in& b);

class get_in
{
private:
int i;
public:
friend istream& operator>>(istream&, get_in&);
get_in(istream& is)
{
is >> *this;
}
get_in()
{
i = 0;
};
};

istream& operator>>(istream& in, get_in& b)
{
in >> b.i;
return in;
}

void main()
{
get_in a(cin);
}

无任何不妥,不过
get_in(istream& is)
{
is >> *this;
}
完全没必要,可以删除,然后在main中
get_in a;
cin >> a ;