我正在探索C++中的ostream
类。我被困在字符串和整数数据类型的cout
的奇怪输出上。
当传递整数或浮点值时,输出正是我所传递的。例如cout.operator<<(10);
打印10
。但是,当将字符串作为参数传递时,它会打印一些十六进制值:
#include <iostream>
#include <string>
using namespace std;
int main() {
const char* str = "aia";
cout.operator<<(str);
return 0;
}
输出:
0x4007e0
。 最佳答案
执行cout.operator<<(str)
时,您将调用cout
的operator <<
成员函数。如果我们看看member functions overloads cout
有什么
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::nullptr_t );
basic_ostream& operator<<( std::basic_streambuf<CharT, Traits>* sb);
basic_ostream& operator<<(
std::ios_base& (*func)(std::ios_base&) );
basic_ostream& operator<<(
std::basic_ios<CharT,Traits>& (*func)(std::basic_ios<CharT,Traits>&) );
basic_ostream& operator<<(
std::basic_ostream<CharT,Traits>& (*func)(std::basic_ostream<CharT,Traits>&) );
如果您注意到,
const char*
没有一个,但是const void*
没有一个。因此,您的const char*
将转换为const void*
,并且该函数的版本将打印指针保存的地址。您需要做的就是调用
operator<<
的non member function overload并可以使用cout << str;
关于c++ - 为什么调用cout.operator <<(const char *)打印地址而不是字符串?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57296899/