我正在编写自己的整数类,它可以处理任何大小的整数。到目前为止,我已经成功重载了以下运算符:=、+、-、*、/、%、>、<、>=、<=、==、!=、+=、-=、*=、/= , 和 %=.
现在,我正在尝试使 <<
过载运算符在以下代码行中模仿 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.
我不确定你从哪里得到的,但第一个参数是左侧参数,在你的情况下是输出流,第二个是写入该输出流的整数类的实例。