我需要哪个操作员超载?

时间:2011-09-18 13:31:46

标签: c++ operator-overloading overloading operator-keyword

如果我想使用这样的话,我必须重载哪个操作符?

MyClass C;

cout<< C;

我班级的输出是字符串。

3 个答案:

答案 0 :(得分:2)

如果您要将operator<<重载为:

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

如果此功能需要访问MyClass的私人成员,那么您必须将friend设为MyClass,或者,您可以将工作委托给某些公共职能部门上课。

例如,假设您的点类定义为:

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

然后你可以将operator<<重载为:

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

您可以将其用作:

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

输出:

{10,20,30}

在线演示:http://ideone.com/zjcYd

希望有所帮助。

答案 1 :(得分:1)

流运营商:&lt;&lt;

您应该将其声明为您班级的朋友:

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
}

答案 2 :(得分:0)

您应该将operator<<实现为免费功能。