Which operator do I have to overload?
Which operator do I have to overlo开发者_如何转开发ad 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
}
You should implement operator<<
as a free function.
精彩评论