加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – object.operator有什么作用?

发布时间:2020-12-16 10:24:53 所属栏目:百科 来源:网络整理
导读:参见英文答案 Why does explicitly calling operator on std::cout cause unexpected output?????????????????????????????????????2个 我看到了以下代码: cout.operator ("Hello"); 并认为它将是相同的: cout "Hello"; 但它打印: 0x46e030 它是如何工作
参见英文答案 > Why does explicitly calling operator<< on std::cout cause unexpected output?????????????????????????????????????2个
我看到了以下代码:

cout.operator << ("Hello");

并认为它将是相同的:

cout << "Hello";

但它打印:

0x46e030

它是如何工作的?它能做什么?

解决方法

object.operator<≤(?);与std :: ostream :: operator<<(std :: ostream&,??)不完全相同,因为它排除了非成员(免费)函数. std :: ostream :: operator<<成员是:

basic_ostream& operator<<( short value );
basic_ostream& operator<<( unsigned short value );
basic_ostream& operator<<( int value );
basic_ostream& operator<<( unsigned int value );
basic_ostream& operator<<( long value );
basic_ostream& operator<<( unsigned long value );
basic_ostream& operator<<( long long value );
basic_ostream& operator<<( unsigned long long value );
basic_ostream& operator<<( float value );
basic_ostream& operator<<( double value );
basic_ostream& operator<<( long double value );
basic_ostream& operator<<( bool value );
basic_ostream& operator<<( const void* value );
basic_ostream& operator<<( std::basic_streambuf<CharT,Traits>* sb);
basic_ostream& operator<<( basic_ostream& st,std::ios_base& (*func)(std::ios_base&) );
basic_ostream& operator<<( basic_ostream& st,std::basic_ios<CharT,Traits>& (*func)(std::basic_ios<CharT,Traits>&) );
basic_ostream& operator<<( basic_ostream& st,std::basic_ostream& (*func)(std::basic_ostream&) );

缺少const char *可能看起来令人困惑,但回想一下,你可以添加自由运算符<<除了上述成员之外,还有其他功能. < ostream的>包括这些:

ostream& operator<<( ostream& os,CharT ch );
ostream& operator<<( ostream& os,char ch );
ostream& operator<<( ostream& os,signed char ch );
ostream& operator<<( ostream& os,unsigned char ch );
ostream& operator<<( ostream& os,const CharT* s );
ostream& operator<<( ostream& os,const char* s );
ostream& operator<<( ostream& os,const signed char* s );
ostream& operator<<( ostream& os,const unsigned char* s );
template< class T >
ostream& operator<<( ostream&& os,const T& value );

通过专门调用object.operator<<(??)重载,你明确告诉它不要使用自由函数,只使用成员函数. “HELLO”的最佳匹配是void *重载,因此它打印了字符串的地址.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读