我有 2 个独立的代码文件。一个是主文件,一个是包含函数的文件。
代码如下:
学生.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
对象。然后我希望能够在我的 main 中的任何地方调用 student.cpp 中的函数。但是,我需要提供给构造函数的值来自代码中名为“wordfile”的文件。因此 Student stud(name, i);
在查找“wordfile”的过程中被调用。但是,我随后希望在 while 循环中为“file2”调用“stud.getRegNo()”,但这当然是不允许的。由于 stud 被用作局部变量,因此它的范围不会达到那么远。
所以我的问题是,无论如何我都可以执行我想做的事情吗?也许通过初始化 Student stud
然后调用 stud(name, i)
然后 stud.getRegNo()
?或者类似的东西?
最佳答案
您可以使用 new
在堆上分配 Student,并将实例保持在两个上下文都可以访问的范围级别。
Student* s;
{ //Context 1
s = new Student();
}
{ //Context 2
int regNo = s->getRegNo();
}
关于C++ - 继承和初始化问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14266149/