C++文件读入与友元函数
class Base {protected:
struct tm* timeinfo;
time_t rawtime;
string password;
public:
int name;
}
class NOW:public Base{
public:
friend ifstream & operator >> (ifstream & input, NOW& a);
string nickname;
}
在后续文件读取中:
NOW* now;
ifstream in("try.txt", ios::in);
if (!in.is_open())
cout << "Error opening file"; exit(1);
while (!in.eof())
{
in>>now->password;//这里会报错,说变量无法访问
}
//可是我不是声明友元函数了,password也不是父类私有而是父类保护,子类可以访问的呀?
求大佬解答 顶,求大佬解答
class Base {
protected:
struct tm* timeinfo;
time_t rawtime;
string password;
public:
int name;
}
class NOW:public Base{
public:
//重载 >> 操作符能这么写吗?
friend ifstream & operator >> (ifstream & input, NOW& a);
//似乎只能这样写
friend istream & operator >> (istream & input ,NOW & a)
{
ifstream in;
...
//因为这个函数是 friend 函数,它不能直接访问类的除静态变量之外的任何成员变量,不管是 private 还是 public,但是
//它可以访问某个对象的任意成员变量。如下
in >> a.password;
return input;
}
string nickname;
}
调用这个重载函数是这样调用的。
NOWnow;
cin >> now;
页:
[1]