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

后端 未结 6 1316
旧时难觅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:17

    std::cout is defined as std::ostream with this definition of operator<<.

    Notably this line:

    template< class CharT, class Traits >
    basic_ostream& operator<<( basic_ostream& os,
                                         const char* s );
    

    This gets selected when you use << with an argument of type char*.

    The case of any other non-char pointer type goes here:

    basic_ostream& operator<<( const void* value );
    

    This continues to std::num_put which is made for formatting numeric values. Therefore, the pointer is interepreted numerically like %p in C formatting functions.

提交回复
热议问题