cout << with char* argument prints string, not pointer value

后端 未结 6 1318
旧时难觅i
旧时难觅i 2020-11-21 07:39

This:

const char * terry = \"hello\";
cout<

prints hello instead of the memory address of the \'h\'.

6条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-21 08:06

    The << operator on std::cout is overloaded. Its behavior depends on the type of the right operand. (It's actually several different functions, all named operator<<; the compiler decides which one to call.)

    If you give it a char* or const char*, it treats the operand as a pointer to (the first character of) a C-style string, and prints the contents of that string:

    const char * terry = "hello";
    cout << terry; // prints "hello"
    

    If you give it a char value, it prints that value as a character:

    cout << *terry;   // prints "h"
    cout << terry[0]; // the same
    

    If you give it a pointer of type void*, it prints that pointer value (in some implementation-defined way, typically hexadecimal):

    cout << static_cast(terry); // prints something like 0x4008e4
    

    Treating a char* or const char* as a pointer to a C-style string is a special case, and the only one (that I can think of) that causes operator<< to print something other than the value of the operand. The reason for this goes back to C++'s roots in C, which doesn't have a "string" type and manipulates strings via char* pointers.

    There are numerous other overloads for operator<<, for various integer and floating-point numeric types, for std::string, and so forth.

提交回复
热议问题