c++ - 在 C 中工作,但在 C++ 中不工作

标签 c++ c

<分区>

以下代码可以在 C 中编译,但不能在 C++ 中编译:

int *ptr = 25; //why not in C++?

错误

prog.cpp: In function ‘int main()’:
prog.cpp:6:11: error: invalid conversion from ‘int’ to ‘int*’ [-fpermissive]
  int *ptr = 25;

但这在 C 和 C++ 中编译:

int *ptr = 0;  //compiles in both

为什么分配 0 可以正常工作而其他数字不起作用?

最佳答案

因为在 C++ 中不能将 int 隐式转换为 int*,但是由于历史原因,0 可以,因为它经常用作NULL.

如果你想在 C++ 中这样做,你需要显式地将数字转换为指针:

int *ptr = reinterpret_cast<int*>(25);

关于c++ - 在 C 中工作,但在 C++ 中不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45493010/

相关文章:

c++ - 平均功能不正确

c++ - Qt QApplication::commitData、Windows 关闭、困惑的文档

c - 从 C 中的字符串数组打印

c - 将前导零插入整数

c++ - std::function 作为方法参数

c++ - 带有字符串/八进制的 int lambda 表达式? (C++)

c++ - Base64 encode一个XXTEA加密字符串错误

c - 使用变量中的数组初始化结构

c - 了解 ATMEGA168A 下的 UART

c - 区分同一 NAT 后面的多个客户端