Question

Please.help me solving this strange compile error. I am redefining the operator << for my class Student,but at "s.name" this error appears. The variable s.name is a string...

ostream &operator<<(ostream& output, Student &s)
{
output<<"\nIme: "<<s.name<<"\nFakulteten nomer: "<<s.fakn<<"\nSreden uspeh: "<<s.srus<<endl;
return output;
}

Here is the variables definition:

class Student{

private:
string name;
string fakn;
Date date;
double srus;

The redefinition function is defined as friend in my class:

friend ostream &operator<<(ostream &stream, Student &s);    
Was it helpful?

Solution 2

You need to create 2 functions:

string Student::getAsString()const{
 ostringstream oss;
 oss << "Student name: " << name  << "   "  << fakn << "   " << srus; //etc
 return oss.str();
}


ostream & operator<<( ostream & exit, const Student & ob){
  return exit << "Exit:" << ob.getAsString() << endl;
}

And dont forget to add the respective libraries:

 #include <string>
 #include <sstream>
 #include <iostream>

OTHER TIPS

Student::name is private so it can't be accessed by operator<<. You need to make variable public, or create public getter for it, or make operator<< friend of Student class so that it can access it's private members.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top