从文件c ++中读取类对象(私有成员变量)

时间:2018-10-05 15:30:15

标签: c++ class filestream

我正在学习如何使用对象,但是被卡住了,最接近的答案是Read class objects from file c++。 在这个问题中:

如果将成员变量声明为私有的,您将如何执行相同的任务?

1 个答案:

答案 0 :(得分:1)

尝试类似的操作

person.txt的内容

John California 3683893

Stalin Russia 489895

示例代码:

#include<iostream>
#include <fstream>
#include <vector>
#include <string>

class person
{
private:
    std::string _name;
    std::string _address;
    unsigned int _phone;
public:
    person(const std::string& name, const std::string& address, unsigned int phone)
        :_name(name),_address(address),_phone(phone)
    {}
    std::string getName() const { return _name; }
    std::string getAddress() const { return _address; }
    unsigned int getPhone() { return _phone; }
};

int main()
{
    std::vector<person> persons;
    std::string name;
    std::string address;
    unsigned int phone;
    std::ifstream fs;
    fs.open("person.txt");
    if (fs.is_open()) {
        while (std::getline(fs, name, ' ') && std::getline(fs, address, ' ') &&
            (fs >> phone))
        {
            persons.push_back(person(name,address,phone));
        }
    }

    for (auto p : persons) {
        std::cout << p.getName() << " " << p.getAddress() << " " << p.getPhone() << '\n';
    }

    return 0;
}