Julian
Julian

Reputation: 21

Which operator do I have to overload?

Which operator do I have to overload if I want to use sth like this?

MyClass C;

cout<< C;

The output of my class would be string.

Upvotes: 0

Views: 102

Answers (3)

thiton
thiton

Reputation: 36049

You should implement operator<< as a free function.

Upvotes: 0

Luchian Grigore
Luchian Grigore

Reputation: 258618

The stream operator: <<

You should declare it as a friend of your class:

class MyClass
{
    //class declaration
    //....
    friend std::ostream& operator<<(std::ostream& out, const MyClass& mc);
}

std::ostream& operator<<(std::ostream& out, const MyClass& mc)
{
    //logic here
}

Upvotes: 1

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361532

if you've to overload operator<< as:

std::ostream& operator<<(std::ostream& out, const MyClass & obj)
{
   //use out to print members of obj, or whatever you want to print
   return out;
}

If this function needs to access private members of MyClass, then you've to make it friend of MyClass, or alternatively, you can delegate the work to some public function of the class.

For example, suppose you've a point class defined as:

struct point
{
    double x;
    double y;
    double z;
};

Then you can overload operator<< as:

std::ostream& operator<<(std::ostream& out, const point & pt)
{
   out << "{" << pt.x <<"," << pt.y <<"," << pt.z << "}";
   return out;
}

And you can use it as:

point p1 = {10,20,30};
std::cout << p1 << std::endl;

Output:

{10,20,30}

Online demo : http://ideone.com/zjcYd

Hope that helps.

Upvotes: 2

Related Questions