How to define class operator << in C ++

For a class like:

class Person
{
private:
    char *name;

public:
    Person()
    {
        name = new char[20];
    }
    ~Person()
    {
        delete [] name;
    }
}

      

I want to print to print the name from an instance of this example using a statement like the following:

cout << myPerson << endl;

      

What do I need to do to define an inference statement <<

for this class?

+1


source share


2 answers


add this to the class:

friend std::ostream& operator<< (std::ostream& out, const Person& P);

      



and then define the <operator something like this:

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

      

+12


source


Define a member function print () that takes an ostream value as an argument. Then let the overloaded operator <<call this member function. This way, you can avoid using a friend. Example:



void YourClass::print(ostream& out) const
{
    //implement printing ...
}
ostream& operator<<(ostream& out, const YourClass& m)
{
    m.print(out);
    return out;
}

      

+3


source







All Articles