char *a, *b; a = &ch1; b = &ch2;
cout << a << " " << b << endl; // 輸出 "I Q" 而非地址
std::ostream 為 char* 提供了專門的重載運算符 operator<<(const char*),默認行為是**將其視為 C 風格字符串(以空字符結尾)輸出內容**,而非輸出指針地址。這是為了方便直接打印字符串字面量和字符數組。
cout << static_cast<const void*>(a) << " " << static_cast<const void*>(b) << endl;
// 或
cout << (void*)a << " " << (void*)b << endl;
// 或 C++17
cout << std::addressof(ch1) << " " << std::addressof(ch2) << endl;
強制轉換為 void* 會匹配 operator<<(const void*),輸出十六進制地址值。
int*、double* 無專用重載,匹配 const void* 版本,直接輸出地址。char*、signed char*、unsigned char* 觸發字符串輸出版本。static_cast<void*>(ptr) 或 std::addressof。cout << ptr;若字符串可能不以 \0 結尾,用 cout.write(ptr, len)。理解標準庫的重載決策規則,能避免此類「明明是指針卻輸出內容」的困惑。