我需要重载哪个运算符

Which operator do I have to overload?

本文关键字:运算符 重载      更新时间:2023-10-16

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

MyClass C;
cout<< C;

我的类的输出将是string

如果您必须重载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的私有成员,那么你必须使它成为MyClassfriend,或者,你可以将工作委托给类的某个公共函数。

例如,假设你有一个点类定义为:
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

希望对你有帮助。

流操作符:<<

你应该将它声明为你的类的友元:

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<<实现为一个自由函数