Search code examples
c++classoperator-overloadingredefine

Redefinition of operator << in C++


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 ?


Solution

  • First of all the class definition shall be ended with a semicolon.

    class Person {
    // ...
    };
    

    Secondly you are speaking about overloading an operator not an operand.

    Operator << is a binary operator that is applied to two operands. If you want to overload this operator for standard output stream and your class then you should specify as the first parameter standard output stream. Also it is much better to pass an object of your class by const reference. So the declaration will look as

    std::ostream & operator <<( std::ostream &os, const Person &person );
    

    That this operator could access data members of your class that are defined as private it should be declared as a friend function of the class or has access to public methods of the class that provide access to private data members.

    For example

    class Person {
    private:
         string name;
         unsigned long personId;
         string address;
         friend std::ostream & operator <<( std::ostream &os, const Person &person );
    
    public:
        Person(string name2,unsigned long id,string adr) {
        name = name2;
        personId = id;
        address = adr;
    };
    

    Or

    class Person {
    private:
         string name;
         unsigned long personId;
         string address;
         ostream & out( std::ostream &os ) const;
    
    public:
        Person(string name2,unsigned long id,string adr) {
        name = name2;
        personId = id;
        address = adr;
    };
    

    and

     std::ostream & operator <<( std::ostream &os, const Person &person )
     {
         return ( person.out( os ) );
     }