简体   繁体   中英

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.

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.

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
}

您应该将operator<<作为自由函数实现。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM