Reputation: 147
I have 2 separate code files. One is a main file and one is a file which includes functions.
The code can be viewed below:
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;
}
}
}
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();
}
}
What I ideally want to do is use the constructor in my student.cpp
to create a student
object. I then want to be able to make calls to functions in student.cpp anywhere in my main. However, the values that I need to provide to the constructor come from a file called 'wordfile' in my code. Therefore Student stud(name, i);
is being called in the while look for 'wordfile'. However, I then wish to call 'stud.getRegNo()' in the while loop for 'file2', but of course this won't be allowed. As stud is being used as a local variable so its scope doesn't reach that far.
So my question is, is there anyway that I can carry out what I want to do? Maybe by initializing Student stud
and then called stud(name, i)
then stud.getRegNo()
? Or something along those lines?
Upvotes: 0
Views: 129
Reputation: 186
Instead of using vectors (?), what you probably need is a std::map so that you know which student to pick.
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();
....
Upvotes: 0
Reputation: 5534
You could allocate Student on the heap using new
and keep the instance at a scope level accessible by both contexts.
Student* s;
{ //Context 1
s = new Student();
}
{ //Context 2
int regNo = s->getRegNo();
}
Upvotes: 2