0

I have a question about operators and how to overload them. There is an example of code and I'm overloading operator<< but it doesn't work. There is class that I use:

class CStudent{ //class for students and their attributes int m_id; int m_age; float m_studyAverage; public: CStudent(int initId, int initAge, float initStudyAverage): m_id(initId), m_age(initAge), m_studyAverage(initStudyAverage){} int changeId(int newId){ m_id = newId; return m_id; } int increaseAge(){ m_age++; return m_age; } float changeStudyAverage(float value){ m_studyAverage += value; return m_studyAverage; } void printDetails(){ cout << m_id << endl; cout << m_age << endl; cout << m_studyAverage << endl; } friend ostream operator<< (ostream stream, const CStudent student); }; 

Overload:

ostream operator<< (ostream stream, const CStudent student){ stream << student.m_id << endl; stream << student.m_age << endl; stream << student.m_studyAverage << endl; return stream; } 

And there is main method:

int main(){ CStudent peter(1564212,20,1.1); CStudent carl(154624,24,2.6); cout << "Before the change" << endl; peter.printDetails(); cout << carl; peter.increaseAge(); peter.changeStudyAverage(0.3); carl.changeId(221783); carl.changeStudyAverage(-1.1); cout << "After the change" << endl; peter.printDetails(); cout << carl; return 0; } 

Where is the problem?

4
  • 1
    What does not work? Is there a compiler error message or a run-time bug? Commented May 12, 2013 at 0:48
  • 1
    operator<< should take a reference to an ostream (std::ostream &) as it's 1st parameter, and it should also take a const reference (CStudent const &) as it's 2nd parameter. Last but not least it should return a reference to the passed-in ostream. So to sum it up: friend std::ostream & operator<<(std::ostream & stream, CStudent const & student) Commented May 12, 2013 at 0:48
  • 1
    @pmr there is an error i cant compile it Commented May 12, 2013 at 0:51
  • @ChrisBarlow: So tell us what error you get! Don't make it unnecessarily hard to help you by withholding information. Commented May 12, 2013 at 0:54

1 Answer 1

2

The problem here is you need to learn what references are and the difference between std::ostream and std::ostream& is.

std::ostream& operator<< (std::ostream& stream, const CStudent& student)

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you that was it, dont know how i missed it

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.