overloaded operator question
Dec 5, 2013 at 2:52am UTC
Okay so I have a pretty simple question. I'm just trying to figure out what exactly this one variable is in an example we were given to help us understand overloaded operators. It's called input (under the overloaded operator function). I just am not seeing what exactly it is. Here are the three files we were given to examine (I cut them down to just what you need I believe):
Student.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
#include<string>
#include<vector>
using namespace std;
#ifndef STUDENT_H
#define STUDENT_H
class Student{
friend ostream &operator <<(ostream &, Student &);
friend ifstream &operator >>(ifstream &, Student &);
public :
Student(){};
string get_name();
void get_my_courses( vector<string> &courses);
bool operator <( Student & );
private :
string last;
string first;
vector<string> my_courses;
};
#endif
student.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
ifstream &operator >>(ifstream &input, Student &some){
string s;
getline(input, s);
istringstream istr(s);
istr >> some.last;
istr >> some.first;
vector<string> v;
while ( !istr.eof()){
istr >> s;
if (s != "" )
v.push_back(s);
}
some.my_courses = v;
return input;
}
ostream &operator <<(ostream &out, Student &some){
out << "Student: " << some.get_name() << endl;
out << "Courses taken: " ;
for (int i = 0; i < some.my_courses.size(); i++)
out << some.my_courses[i] << " " ;
out << endl;
}
student_main.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
#include<iostream>
#include<fstream>
#include<string>
#include<vector>
using namespace std;
#include "student.h"
int main( int argc, char *argv[]){
if (argc < 2)
{
cout << "Enter input file" << endl;
exit(0);
}
string input_file = argv[1];
ifstream inf;
inf.open(input_file.c_str());
Student ast, ast2;
inf >> ast;
cout << "The first student: " << endl << endl;
cout << ast << endl;
inf >> ast2;
cout << "The second student: " << endl << endl;
cout << ast2 << endl;
if ( ast < ast2 )
cout << ast << "is alphabetically preceding\n" << ast2 << endl;
else
cout << ast2 << "is alphabetically preceding\n" << ast << endl;
inf.close();
}
Last edited on Dec 5, 2013 at 2:53am UTC
Topic archived. No new replies allowed.