// person.h
#ifndef PERSON_H
#define PERSON_H
#include <string>
#include <vector>
class Person {
public:
Person(); // デフォルトコンストラクタ
Person(const std::string& name, int age, const std::string& gender); // コンストラクタ
static std::vector<Person> readFromFile(const std::string& filename);
void displayData() const;
private:
std::string name;
int age;
std::string gender;
};
#endif // PERSON_H
// person.cpp
#include "person.h"
#include <iostream>
#include <fstream>
// デフォルトコンストラクタの実装
Person::Person() : age(0) {}
// コンストラクタの実装
Person::Person(const std::string& name, int age, const std::string& gender)
: name(name), age(age), gender(gender) {}
// データをファイルから読み込むメソッドの実装
std::vector<Person> Person::readFromFile(const std::string& filename) {
std::vector<Person> people;
std::ifstream infile(filename);
if (!infile) {
std::cerr << "ファイルを開けませんでした" << std::endl;
return people;
}
Person person;
while (infile >> person.name >> person.age >> person.gender) {
people.push_back(person);
}
infile.close();
return people;
}
// データを表示するメソッドの実装
void Person::displayData() const {
std::cout << "名前: " << name << ", 年齢: " << age << ", 性別: " << gender << std::endl;
}
// main.cpp
#include <iostream>
#include <vector>
#include "person.h"
int main() {
std::vector<Person> people = Person::readFromFile("data.txt");
// データを表示して確認します
for (const auto& person : people) {
person.displayData();
}
return 0;
}