c++ - 我必须重载哪个运算符?

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

如果我想像这样使用某物,我必须重载哪个运算符?

MyClass C;

cout<< C;

我的类(class)的输出是字符串。

最佳答案

如果你要重载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的私有(private)成员, 那么你必须做到 friendMyClass ,或者,您可以将工作委托(delegate)给类的某些公共(public)函数。

例如,假设您将一个点类定义为:

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

希望对您有所帮助。

关于c++ - 我必须重载哪个运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7461793/

相关文章:

c++ - Qt - 当一个类中有多个 QTcpSocket 时,如何知道哪个 QTcpSocket 发出了 readRead 信号?

c++ - 重载赋值操作/流

C++竞技编程: Simplifying expressions under modulo N

python - 关于 __getattr__ 和 __getattribute__ 的一些问题?

c# - 再次加载 Form1 的可视化 C# 代码

c++ - 什么是 std::map<K,V>::map;以及如何知道在实现/使用 STL 容器和函数时使用什么命名空间?

c++ - 如何使用 ffmpeg 录制 Windows 屏幕

c++ - 我如何获得代码::blocks to keep the libraries configured after code::blocks restarts?

c++ - C++ 中的 Variadic 宏未按预期工作

c# - 在 C# 中解决方法重载的优先规则是什么?