我有一个学生类,该类具有从文本文件读取学生对象并将其添加到学生Vector的功能。没关系,可以正常使用。我的student.cpp文件中有此功能。 (我认为这是正确的。)
如何将这个向量从student.cpp返回到主要位置,以便在其中访问元素,对其进行编辑和排序等。
student.cpp
#include "pch.h"
#include "q1studentType.h"
q1studentType::q1studentType(std::string sFN, std::string sLN, std::string ts)
{
studentFName = sFN;
studentLName = sLN;
testScore = ts;
}
void q1studentType::printStudent()
{
std::cout << studentFName << " " << studentLName << "\t(" << testScore << " / "<< grade << ")" << std::endl;
}
std::vector<q1studentType> q1studentType::initStudents() {
std::vector<q1studentType> students;
std::ifstream inFile("students.txt");
for (q1studentType i;
getline(inFile, i.studentFName, ',')
&& getline(inFile, i.studentLName, ',')
&& getline(inFile, i.testScore)
; )
{
students.push_back(i);
i.printStudent();
}
return students;
}
主要
int main() {
//What I want to say in my head
std::vector<q1studentType> students = q1studentType.initStudents();
}
我要以正确的方式解决这个问题吗?预先感谢
答案 0 :(得分:1)
您的代码有问题:
在声明中(通常在头文件q1studentType.h中)将initStudents()设为公共和静态
public: static std::vector<q1studentType> q1studentType::initStudents();
.cpp中的代码对我来说没问题。
并在main.cpp中将其命名为正确的
auto students = q1studentType::initStudents();