继承和初始化的问题
C++ - Problems with inheritance and initialization
我有2个独立的代码文件。一个是主文件,一个是包含函数的文件。
代码可以在下面查看:
Student.cpp
Student::Student(const string &name, int regNo) : Person(name)
{
map<string, float> marks;
this->name = name;
this->regNo = regNo;
}
int Student::getRegNo() const
{
return regNo;
}
void Student::addMark(const string& module, float mark)
{
map<string, float>::const_iterator it;
marks.insert(make_pair(module, mark));
for (it = marks.begin(); it != marks.end(); it++)
{
if(it->second !=0){
marks[module] = mark;
}
}
}
main.cpp
Student stud(name, i);//this is what I want to do
if(wordfile.is_open() && file2.is_open())
{
if(!wordfile.good() || !file2.good())
{
cout << "Error reading from file. " << endl;
}
while(wordfile.good())
{
getline(wordfile, s1);
istringstream line(s1);
line >> i;
line >> name;
Student stud(name, i);
cout << stud.getRegNo() << endl;
itR.push_back(stud.getRegNo());
vS.push_back(stud);
}
wordfile.close();
while(file2.good())
{
getline(file2, s2);
istringstream line(s2);
line >> reg;
line >> mod;
line >> mark;
stud.getRegNo();
}
file2.close();
}
}
理想情况下,我想做的是使用student.cpp
中的构造函数来创建student
对象。然后,我希望能够在我的主程序的任何地方调用student.cpp中的函数。但是,我需要提供给构造函数的值来自代码中名为"wordfile"的文件。因此,Student stud(name, i);
在寻找"wordfile"的同时被调用。然而,我希望在'file2'的while循环中调用' student . getregno()',但当然这是不允许的。因为stud被用作局部变量,所以它的作用域没有达到那么远。
所以我的问题是,有没有什么方法可以让我完成我想做的事情?也许通过初始化Student stud
,然后调用stud(name, i)
,然后stud.getRegNo()
?或者类似的东西?
您可以使用new
在堆上分配Student,并将实例保持在两个上下文都可以访问的范围级别。
Student* s;
{ //Context 1
s = new Student();
}
{ //Context 2
int regNo = s->getRegNo();
}
不用vector(?),你可能需要的是std::map,这样你就知道该选哪个学生了。
std::map<int, Student*> students;
while(wordfile.good())
{
getline(wordfile, s1);
istringstream line(s1);
line >> i;
line >> name;
students[i] = new Student(name, i);
}
wordfile.close();
while(file2.good())
{
getline(file2, s2);
istringstream line(s2);
line >> reg;
line >> mod;
line >> mark;
students[reg]->addMark(mod, mark);
}
file2.close();
....
相关文章:
- C++转换参数初始化问题
- 运行时C++数组初始化问题
- wxWidgets 拖放文件事件处理程序初始化问题(无效static_cast)
- C++初始化具有 int 0 问题的unique_ptr
- 使用初始化列表填充C++中的多维结构数组时出现问题
- 它解决了什么问题,对于非真空初始化,生命周期在初始化之前就开始了
- 在构造函数 c++ 中初始化属性时出现问题
- 我是否需要在虚拟继承类的构造函数中初始化基类以解决菱形继承问题?
- (2 问题)"类"类型重新定义(即使 #pragma 一次),以及静态函数内的静态成员对象初始化?
- shared_ptr类的向量的向量初始化问题
- public:静态常量字符串声明/初始化问题
- 初始化与类类型相同的静态成员(静态初始化顺序问题)
- 使用 true 初始化布尔数组时出现问题
- 为什么C++中的大括号初始化可以解决STL容器的初始化问题
- 程序在没有输入的情况下退出,它有基本的,驱动的类属性初始化问题
- C++中构造函数的对象初始化出现问题
- 初始化com对象的问题
- 初始化多个纹理 OpenGL、SDL C++ 时出现问题
- 共享库中 __attribute__((构造函数)) 的全局/静态变量初始化问题
- 理解向量初始化时出现问题