Hi,
I am writing a piece of code for a student database.
I have one abstract base class named student and three classes (physics student, biology student and chemistry student) derived from student.
I want to overload the insertion operator (<<) so that at some point in main I can print a students details to the screen.
Here is the code for how I have done it for my physics student class:
namespace phy_namespace{
class phy_student : public student{
protected:
string name;
int id;
double av1;
double av2;
double av3;
double course_av;
vector<pair<double,string>> core_courses1;
vector<pair<double,string>> core_courses2;
vector<pair<double,string>> core_courses3;
vector<pair<double,string>> option_courses1;
vector<pair<double,string>> option_courses2;
vector<pair<double,string>> option_courses3;
pair<double,string> dissertation;
public:
phy_student(string NAME, int ID) : name(NAME), id(ID), av1(0), av2(0), av3(0) {;}
~phy_student() {;}
void add_core_courses1();
void add_core_courses2();
void add_core_courses3();
string get_name() {return name;}
friend ostream & operator<<(ostream &cout, phy_student &student);
};
}
....................
ostream & phy_namespace::operator<<(ostream &cout, phy_student &student){
cout<<"First year courses:"<<endl<<endl;
vector<pair<double,string>>::iterator it;
for(it=student.core_courses1.begin(); it!=student.core_courses1.end(); it++){
cout<<"Course: "<<it->second<<" ("<<it->first<<" %)"<<endl;
}
return cout;
}
At the moment I am just trying to print out the students first year courses and corresponding grade. The courses and grades are stored in a vector of pairs.
My problem is this.
In main, my students are stored using a map, with their ID number as the identifier and a base class pointer as the second bit (I don't know what you call it).
i.e.
typedef map<int,student*> student_map;
In main I give the user the option to implement a search, which uses the following code:
void search(student_map &student, int ID){
student_map::iterator it;
it = student.find(ID);
if(it != s.end()){
cout<<"Found student with student number " << ID << ", his / her name is: "<<it->second->get_name()<<endl<<endl;
cout<<*(it->second);
}
else cout<<"Sorry, there is no student number with student number " << ID <<" in database"<<endl;
}
However, the line:
cout<<*(it->second);
returns an error. I cannot see why because the iterator "it" points to whichever pair in the map that correspond to the ID number. Therefore "it->second" points to the base class pointer student, and dereferencing this should be the object itself, for which I have defined the overloaded insertion operator.
Any help would be greatly appreciated.
Thanks, Dave