【问题标题】:Error when type casting. Confusion [duplicate]类型转换时出错。混乱[重复]
【发布时间】:2016-09-20 20:42:29
【问题描述】:
double d = 43.56;
int m = d;
cout<<(char *)&m<<endl; //works fine, it prints: + = 43
cout<<(char *)m<<endl; //this doesn't work, char can't be made into a  pointer
cout<<reinterpret_cast<char *>(&m)<<endl; //works fine, prints: +
cout<<static_cast<char *>(&m)<<endl; //Does not work

我的问题是,为什么最后一行代码不起作用?

编译器错误消息:从 int* 到类型 char* 的 static_cast 无效

static_cast 不应该可以转换吗?

提前致谢。

【问题讨论】:

  • 您是否希望它以字符串形式打印43
  • 我不明白。为什么(char *) m 不起作用?我们在嵌入式系统中经常使用它来将硬件组件的地址分配给指针。
  • 您可能会将转换与operator&lt;&lt; 的可用重载混淆。例如cout 将打印char * 作为字符串;但void * 作为指针。
  • 所有 4 cout 行都是假的。你为什么要这样做。

标签: c++ casting type-conversion


【解决方案1】:

Here 是使用static_cast 可以完成的完整列表。和 没有选项可以将指向一个类的指针转换为指向另一个不相关类的指针。仅仅是因为这不是标准的 C++ 行为。
然而,人们仍然可以使用 c 风格的演员表,reinterpret_cast,甚至可以使用 union 进行“演员表”。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-05
    • 1970-01-01
    • 2017-02-11
    • 2011-08-21
    • 2021-10-13
    • 2020-04-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多