读取文本文件并将数据存储在类的私有成员变量中-C++

Reading a Text File and storing the data in Private member variables of a Class - C++

本文关键字:成员 变量 -C++ 文件 取文本 存储 数据 读取      更新时间:2023-10-16

我有一个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;
}

问题:当变量是私有并且只能使用settergetter函数访问时,如何重载>>运算符,以便将文本文件中的数据存储在相应的变量中?

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,然后可以直接输入到私有变量中。对于输入和输出运算符,使它们成为友元函数是非常常见的。