I am new to the whole 'Operator Overload' world. I am attempting to overload the << operator but I'm unsure how to implement it properly. I have written a declaration and a function (not sure either work), but my real issue is how do I call this thing? Any help, advice, tips, and suggestions are greatly appreciated!
// FRIEND FUNCTIONS
// Modified this to fit code suggested by vlad from moscow (Thanks vlad)
friend ostream &operator<<(ostream &out, const Statistician &s);
int main()
{
//Declare variables
Statistician S1;
S1.Next_Number();
//Changed this according to vlad's suggestion
cout << S1;
//Exit program
return EXIT_SUCCESS;
}
double Statistician::GetLast()
{
return Last;
}
ostream &operator<<(ostream &outs, const Statistician &s)
{
outs << "The last number of the sequence is: " << s.GetLast() << endl;
return outs;
}
error: passing 'const Statistician' as 'this' argument of 'double Statistician::GetLast()' discards qualifiers
if you have a const object (in this case, 's' in your << operator), you cannot call non-const member functions on it (since they might change its state, breaking the constness).
Therefore you can only call const members.
Since GetLast does not change anything in the class, you can make it const: