继承和初始化的问题

C++ - Problems with inheritance and initialization

本文关键字:问题 初始化 继承      更新时间:2023-10-16

我有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();
    ....