首页 > 解决方案 > 我想从文本文件中获取信息并将该信息分配给类对象

问题描述

为什么编译器会抛出错误:'Student::Student'的使用无效|

这是内容文件(ListOfStudent):1234 46567 这是我的代码:

class Student
{string ML,MSV;
public:
    Student();
    Student(string ML,string MSV );
    ~Student();
    void Out();
};
int main()

{
    vector<Student>ListOfStudent;
    {
        ifstream inf("ListOfStudentFile");
        Student st;
        while(inf){
            string ML,MSV;
             inf>>ML>>MSV;
             st.Student(ML,MSV);
            ListOfStudent.push_back(st);
        }
    }

    return 0;

}
Student::Student(string ML,string MSV)
{
    this->ML=ML;
    this->MSV=MSV;

}

标签: c++codeblocks

解决方案


您不能显式调用构造函数。你应该写:

while(inf){
            string ML,MSV;
             inf>>ML>>MSV;
            ListOfStudent.push_back(Student(ML,MSV));
        }

按照 Hemil 的建议,如果您使用的是 C++ 11,则可以通过直接传递构造函数的参数来避免构造临时变量,如下所示:

while(inf){
            string ML,MSV;
             inf>>ML>>MSV;
            ListOfStudent.emplace_back(ML,MSV);
        }

对于像你这样的简单结构,无论如何它都不应该有任何区别,所以使用你喜欢的任何东西。


推荐阅读