读取文本文件并将数据存储在类的私有成员变量中-C++
Reading a Text File and storing the data in Private member variables of a Class - C++
我有一个myFile.txt
文件,它包含学生的名字、姓氏和ID,格式如下
First-Name Last-Name ID
<--这一行不包括在文件中
Steve Smith 12345
<--这一行包含在文件中
我还有一个类Student
,看起来像
class Student
{
private:
std::string firstName;
std::string lastName;
int id;
public:
Student();
Student(std::string fname, std::string lname, int i);
~Student();
void setFirstName(std::string fnam);
std::string getFirstName();
void setLastName(std::string lnam);
std::string getLastName();
void SetID(int i);
int getID();
};
我想读取myFile.txt
文件,并将信息存储在学生类的各个私有成员变量中。
我知道我必须重载>>
运算符,但当变量为私有时,我不知道如何将文件中的数据存储到相应的变量中。
为了写入文件,我重载了<<
运算符,如下所示。
std::ostream& operator << (std::ostream &out, Student &stu)
{
out << stu.getFirstName() << " " << stu.getLastName() << " " << stu.getID() << std::endl;
return out;
}
问题:当变量是私有并且只能使用setter
和getter
函数访问时,如何重载>>
运算符,以便将文本文件中的数据存储在相应的变量中?
std::istream& operator >> (std::istream &in, Student &stu)
{
in >> //what do i write here ? do i have to call the setter functions ? if so, how ?
return in;
}
如果你想从普通的旧std::cin
中读到这样的东西,你会怎么做?
输入运算符也是如此。读入三个不同的变量,并用它们调用setter函数。
您还可以使输入运算符成为类的friend
,然后可以直接输入到私有变量中。对于输入和输出运算符,使它们成为友元函数是非常常见的。
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 内置函数可查看CPP中的成员变量
- 是否可以初始化不可复制类型的成员变量(或基类)
- 将包含C样式数组的对象初始化为成员变量(C++)
- 为什么我不能在一个类的不同行中声明和定义成员变量?
- 在循环中按顺序遍历成员变量
- c++类声明时,相同的例程,不同的成员变量类型
- 如何从另一个文件继承私有成员变量和公共函数
- 在C++类中,是否必须初始化作为数组的成员变量
- 如何从子成员函数修改父公共成员变量
- 我可以在 C++ 中将数据成员/变量从其定义之外添加到结构中吗?
- 从私有成员变量的成员方法返回unique_ptr
- 在派生类中使用基类的私有成员变量的最佳方法
- 静态 constexpr 类成员变量对多线程读取是否安全?
- C++:是否可以使用非静态成员变量模板?
- 打印所有继承的类成员变量和方法
- 如何在复杂继承中访问静态成员变量
- 为什么我不能在返回 const 的布尔函数中为类成员变量赋值?C++
- 成员变量与函数概念检查