我正在探索ostreamC ++中的类。我被困在cout字符串和整数数据类型的奇怪输出上。
当传递整数或浮点值时,输出正是我所传递的。例如cout.operator<<(10);印刷品10。但是,当将字符串作为参数传递时,它会打印一些十六进制值:
#include <iostream>
#include <string>
using namespace std;
int main() {
const char* str = "aia";
cout.operator<<(str);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:0x4007e0。
Nat*_*ica 30
当您cout.operator<<(str)调用cout的operator <<成员函数时。如果我们看一下成员函数重载 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>&) );
Run Code Online (Sandbox Code Playgroud)
如果您注意到,没有一个代表const char*,但是有一个代表const void*。因此,您const char*将转换为,const void*并且该函数的版本将打印指针保存的地址。
您需要做的是调用非成员函数重载,operator<<并且您可以使用
cout << str;
Run Code Online (Sandbox Code Playgroud)
joh*_*ohn 16
问题是对于某些类型,operator<<它作为成员的重载ostream,对于某些类型,它作为全局函数的重载。如果const char*是全局函数,那么如果要显式调用运算符,则必须编写
operator<<(cout, str);
Run Code Online (Sandbox Code Playgroud)
但是对于整数类型,您必须编写
cout.operator<<(num);
Run Code Online (Sandbox Code Playgroud)
您发布的代码中发生的是,const void*正在调用for的重载,这就是为什么看到十六进制数字的原因。