c++ - 如何正确重载 << 运算符?

标签 c++ integer operator-overloading operators outputstream

<分区>

我正在编写自己的整数类,它可以处理任何大小的整数。到目前为止,我已经成功重载了以下运算符:=、+、-、*、/、%、>、<、>=、<=、==、!=、+=、-=、*=、/= , 和 %=.

现在,我正在尝试使 << 过载运算符在以下代码行中模仿 int 的行为:

int a = 5;
std::cout << a;

我一直在研究如何做到这一点,到目前为止我发现的是:

std::ostream& operator<<(std::ostream& os, const T& obj)
{
  // Write obj to stream
  return os;
}

但这似乎适用于如果我想将某些内容流式传输到我的对象中(也就是说,在我的对象的右侧有一个 <<)。但我想改变 << 的行为当它在我的对象的左侧时。

如何设置 operator<<函数允许我将数据流式传输到 cout(或任何其他 ostream)?

最佳答案

How can I set up the operator<< function to allow me to stream data into cout (or any other ostream)?

你在这里做的方式:

std::ostream& operator<<(std::ostream& os, const T& obj)
{
  // write obj to stream
  return os;
}

正如其他人在评论中有用地指出的那样,您需要将它放在整数类之外才能成为“自由函数”。它可能仍然是您的整数类的成员,但是,是的,就是这样。

But this seems to be for if I wanted to stream something into my object. (i.e. having the << on the right side of my object). But I want to change the behavior of << when it is on the LEFT side of my object.

我不确定你从哪里得到的,但第一个参数是左侧参数,在你的情况下是输出流,第二个是写入该输出流的整数类的实例。

关于c++ - 如何正确重载 << 运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23446759/

相关文章:

c++ - boost::async - 不确定实现

C++动态库dlopen错误

Windows 批处理文件 : how to compare command line argument to an integer

python - 如何始终获得正输出?

c++ - C++ 中的重载运算符

c++ - 在 O(n) 时间和 O(1) 空间中查找重复项

c++ - 有符号和无符号整数 C++ 实现的区别

C++避免代码重复运算符重载

c++ - C++ 中的辅助运算符问题

c++ - cpp 为什么 s.query 会被覆盖