0

2 つの個別のコード ファイルがあります。1 つはメイン ファイルで、もう 1 つは関数を含むファイルです。

コードは以下で表示できます。

学生.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();
    }
}

私が理想的にやりたいことは、 my でコンストラクターを使用してオブジェクトstudent.cppを作成するstudentことです。次に、メインのどこにいても、student.cpp の関数を呼び出せるようにしたいと考えています。ただし、コンストラクターに提供する必要がある値は、コード内の「wordfile」というファイルから取得されます。そのためStudent stud(name, i);、「wordfile」を探しながら呼び出されています。ただし、「file2」のwhileループで「stud.getRegNo()」を呼び出したいのですが、もちろんこれは許可されません。スタッドはローカル変数として使用されているため、そのスコープはそれほど遠くありません。

だから私の質問は、私がやりたいことを実行できる方法はありますか? たぶん、初期化Student studしてから呼び出しstud(name, i)ますstud.getRegNo()か?またはそれらの線に沿った何か?

4

2 に答える 2

2

を使用してStudentをヒープに割り当てnew、両方のコンテキストからアクセス可能なスコープレベルでインスタンスを維持できます。

Student* s;

{ //Context 1
    s = new Student();
}

{ //Context 2
    int regNo = s->getRegNo();
}
于 2013-01-10T19:56:43.590 に答える
0

ベクトル (?) を使用する代わりに、おそらく必要なのは 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();

    ....
于 2013-01-10T21:30:17.843 に答える