简单的c++运算符重载帮助
如何重载 <<
运算符?从我收到的错误来看,std::cout
似乎不知道如何使用<<
。
这是在一个类中:
// uint64_t UPPER, LOWER;
std::ostream & operator<<(std::ostream & stream){
if (UPPER)
stream << UPPER;
stream << LOWER;
return stream;
}
我收到错误:与“operator<<”不匹配在 'std::cout << test'
这似乎没有意义。
编辑:
this:
std::ostream & operator<<(std::ostream & stream, uint128_t const & val){
if (val.upper())
stream << val.upper();
stream << val.lower();
return stream;
}
和 this:
std::ostream & operator<<(std::ostream & stream, uint128_t val){
if (val.upper())
stream << val.upper();
stream << val.lower();
return stream;
}
都没有改变错误。
How do I overload the <<
operator? From the error I am getting, it seems that std::cout
doesn't know how to use <<
.
This is in a class:
// uint64_t UPPER, LOWER;
std::ostream & operator<<(std::ostream & stream){
if (UPPER)
stream << UPPER;
stream << LOWER;
return stream;
}
I am getting error: no match for 'operator<<' in 'std::cout << test'
which doesn't seem to make sense.
edit:
Neither this:
std::ostream & operator<<(std::ostream & stream, uint128_t const & val){
if (val.upper())
stream << val.upper();
stream << val.lower();
return stream;
}
nor this:
std::ostream & operator<<(std::ostream & stream, uint128_t val){
if (val.upper())
stream << val.upper();
stream << val.lower();
return stream;
}
is changing the error.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
<<
运算符采用两个参数:左侧和右侧。因此,您必须使用两个参数定义该函数:据我所知,您必须在类定义之外定义它。在类定义内部,您只能使用将该类作为左侧的运算符。
The
<<
operator takes two arguments, a left hand side, and a right hand side. Therefore you have to define the function with two parameters:And you have to define it outside of your class definition, as far as I can remember. Inside of the class definition you can only have operators that take that class as the left hand side.
您通常希望
operator<<()
重载成为“自由函数”(在您的类之外),以便它可以自然地绑定到流:然后在您的类中将其声明为
friend
如果有必要,这样它就可以到达类内部:让它成为
friend
的另一种方法(有些人认为这是破坏封装的)是在你的类中拥有一个公共函数类将自身输出到流并调用它在您的operator<<()
重载中:You typically want the
operator<<()
overload to be a 'free function' (outside of your class) so it can bind to the stream naturally:Then inside your class you declare it a
friend
if necessary so it can get to the class internals:An alternative to having this be a
friend
(which some people consider to be breaking encapsulation) is to have a public function in your class that will output itself to a stream and call that in youroperator<<()
overload:类外部的
运算符<<
需要两个参数:operator<<
outside a class requires two arguments: