Redefinition of operator << in C++

user2976091 picture user2976091 · Nov 15, 2013 · Viewed 9.2k times · Source

I know this question might be stupid, but i am new in C++ and i have a lot of problems with redefinitions of operands. What i`m trying to do is to redefine the operand << to print my class "Person" information but it appears compiling error:

class Person {
private:
     string name;
     unsigned long personId;
     string address;
public:
    Person(string name2,unsigned long id,string adr) {
    name = name2;
    personId = id;
    address = adr;
}
void operator<<(Person person) {
     cout<<"Name: "<<person.name<<"  Person ID:  "<<person.personId<<"  Person address:  "<<person.address<<endl;
 }
}

int _tmain(int argc, _TCHAR* argv[])
{
     Person person("Steven",1212121212,"USA");
     cout<<person; //compiling error here

     return 0;
}

What`s the right way to do this ?

Answer

ForEveR picture ForEveR · Nov 15, 2013

operator << is binary operator, so, first parameter for it should be reference to std::ostream object in your case. Since your variables are private - you cannot overload operator << as free function. First parameter for class function is pointer to object of this class, so you should use friend specificator (which grants access to private variables of your class) on the function.

friend ostream& operator << (ostream& os, const Person& person)
{
   os << "Name: "<< person.name << "  Person ID:  "
      << person.personId << "  Person address:  " << person.address << endl;
   return os;
}