为什么不将cout应用于指针以char打印它的地址表示? [英] Why doesn't applying cout to a pointer to char print it address representation?

查看:151
本文介绍了为什么不将cout应用于指针以char打印它的地址表示?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码:

#include <iostream>

int main()
{
    char * a =new char('a');
    std::cout << a << std::endl; // a
    int * i = new int(1);
    std::cout << i << std::endl; // 0x135a5030
}

DEMO

DEMO

以下重载:

ostream& operator<< (bool val);
ostream& operator<< (short val);
ostream& operator<< (unsigned short val);
ostream& operator<< (int val);
ostream& operator<< (unsigned int val);
ostream& operator<< (long val);
ostream& operator<< (unsigned long val);
ostream& operator<< (long long val);
ostream& operator<< (unsigned long long val);
ostream& operator<< (float val);
ostream& operator<< (double val);
ostream& operator<< (long double val);
ostream& operator<< (void* val);

那么为什么结果不同呢?

So why the results are different?

推荐答案

您错过了

template<class charT, class traits>
basic_ostream<charT,traits>& operator<<(basic_ostream<charT,traits>& out, const charT* s);
template<class charT, class traits>
basic_ostream<charT,traits>& operator<<(basic_ostream<charT,traits>& out, const char* s);
template<class traits>
basic_ostream<char,traits>& operator<<(basic_ostream<char,traits>& out, const char* s);
template<class traits>
basic_ostream<char,traits>& operator<<(basic_ostream<char,traits>& out, const signed char* s);
template<class traits>
basic_ostream<char,traits>& operator<<(basic_ostream<char,traits>& out, const unsigned char* s);

。你有UB,因为他们期望以null结尾的字符串。

in §27.7.3.6.4 [ostream.inserters.character]. And you have UB because they expect null-terminated strings.

这篇关于为什么不将cout应用于指针以char打印它的地址表示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆