我想从文本文件中获取信息并将该信息分配给类对象



为什么编译器给我抛出错误:无效使用"学生::学生"|

这是内容文件(学生列表(: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;
}

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

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);
        }

对于像您这样的简单结构,无论如何它应该没有任何区别,因此请使用您喜欢的任何内容。

相关内容

最新更新