3

我看到了以下代码:

cout.operator << ("Hello");

并认为它与以下内容相同:

cout << "Hello";

但它打印:

0x46e030

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

4

2 回答 2

7

打印字符串的重载operator<<是一个自由函数。有点像;

namespace std
{
    ostream & operator<<(ostream &, char const *);
}

(尽管我不确定是否确实如此)。它不是的成员函数std::ostream。通过显式选择成员函数,您可以获得打印指针值的成员函数。

于 2013-07-31T18:30:45.353 回答
5

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*可能看起来令人困惑,但请记住,除了上述成员之外 ,您还可以添加免费函数。 包括这些:operator<<<ostream>

ostream& operator<<( ostream& os, CharT ch );
ostream& operator<<( ostream& os, char 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 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*重载,所以它打印了字符串的地址。

于 2013-07-31T18:35:31.367 回答