c++ - 我想从文本文件中获取信息并将该信息分配给类对象
问题描述
为什么编译器会抛出错误:'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;
}
解决方案
您不能显式调用构造函数。你应该写:
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);
}
对于像你这样的简单结构,无论如何它都不应该有任何区别,所以使用你喜欢的任何东西。
推荐阅读
- xamarin.forms - 如何使用渲染器为表单中的条目控件设置透明边框颜色
- wordpress - 无法访问 wordpress 上的内容,总是重定向到页面 http://localhost/dashboard/
- php - 使用 php 的字母搜索框
- google-apps-script - 如何使用谷歌应用脚本通过 API 更新 Streak 框?
- google-cloud-firestore - 未为集合组中的 arrayContains 生成 Firestore 索引 URL?
- android - 通过 chrome://inspect 调试 WebView 时无法单击截屏
- azure-blob-storage - 是否可以在 blob 上读取实际应用的不可变策略 - 剩余的基于时间的保留天数
- xml - 任何现代浏览器真的没有办法在 XML 文件中应用远程 XSLT 样式表引用吗?
- file-upload - 每次在 Load Runner 中上传具有不同名称的相同文件
- vue.js - 在 vueJS 上使用 PrintJS 打印页面部分