为什么运算子>> (或<<)重载函数需要接收i \ ostream引用吗? [英] Why does operator>> (or <<) overloading function need to receive an i\ostream reference?
问题描述
在cplusplus.com上,我看到ostream
类的成员函数operator<<
看起来像这样:
From cplusplus.com, I saw that ostream
class's member function operator<<
looks like this:
ostream& operator<< (bool val); ostream& operator<< (int val);
....依此类推.
这确实是有道理的,因为当您使用像cout<<x
这样的Cout对象时,您会激活ostream& operator<< (int val)
函数,因此实际上是在Cout对象上使用了<<
运算符.这与其他所有运算符非常相似,并将int
变量发送给函数.当我要流式传输自己的对象时,有什么区别?究竟发生了什么?为什么语法突然是ostream& operator<< (**ostream &os**, object ob)
?
为什么需要添加ostream
var?我仍在使用cout<<ob
,所以不是ostream& operator<< (object obj)
吗?我所通过的只是我的对象. cout
对象已经准备就绪.
It does make sense because when you use the Cout object like cout<<x
you activate the ostream& operator<< (int val)
function, so you actually use the <<
operator on Cout object. This is very much like every other operator and sends the int
variable to the function. What is the difference and what exactly happens when I want to stream an object of my own? Why does the syntax is suddenly ostream& operator<< (**ostream &os**, object ob)
?
Why do I need to add the ostream
var? I am still using cout<<ob
so whay isnt it just ostream& operator<< (object obj)
? All I pass is my object. The cout
object is allready there.
推荐答案
operator<<
通常定义为自由函数;即不是成员函数.由于它是重载的二进制运算符,这意味着它首先获得其左参数,然后获得其右参数.
operator<<
is generally defined as a free function; that is, not a member function. Since it is an overloaded binary operator, that means it get's its left argument first and its right argument second.
operator<<
传统上会返回对其左参数的引用,以启用惯用的输出链.
The operator<<
traditionally returns a reference to its left argument to enable the idiomatic chain of output.
为了使读者容易理解,我倾向于使用lhs
和rhs
缩写来定义我的operator
重载;对于某些类型的T
,operator<<
看起来与此类似.
To make it obvious to the reader, I tend to define my operator
overloads using the lhs
and rhs
abbreviations; an operator<<
would look similar to this, for some type T
.
std::ostream& operator<<(std::ostream& lhs, T const& rhs)
{
// TODO: Do something
return lhs;
}
作为成员函数
与其他二进制文件一样,可以将其定义为成员函数.也就是说,让我们假设您定义了自己的iostream
.除其他事项外,您的类声明可能看起来像这样.同样,T
是一种特殊类型.
As a member function
As with other binary it could be defined as a member function. That is, let us suppose that you with defining your own iostream
. Amongst other things, your class declaration may look like this. Again, T
is a particular type.
class MyIOStream : public iostream
{
public:
MyIOStream& operator<<(T const& rhs);
}
在这种情况下,operator<<
是成员函数.与<<
一样具有相同的语义.
In this case operator<<
is a member function. It has the same semantics when used as <<
.
- C和C ++中的运算符-您所有运算符的摘要可以重载及其典型参数.
- Operators in C and C++ - a great summary of all the operators you can overload and their typical arguments.
这篇关于为什么运算子>> (或<<)重载函数需要接收i \ ostream引用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!