寻找 Explanation of pointer initializing to const int 和 int
Looking for Explanation of pointer initializing to const int and int
我正在完成 C++ Primer 中的练习,并找到了练习 2.32 的在线解决方案。
我了解到以下代码是非法的,因为初始化无法从 int 转换为 int*:
int null = 0, *p = null;
但是,我没有想到的两个提到的解决方案是:
const int null3 = 0, *p3 = null3;
constexpr int null4 = 0, *p4 = null4;
为什么在编译时允许这些没有错误?我仍然期望 p3 和 p4 的初始化需要 & 来表示地址 (&null3, &null4)。
这是我从记事本文件中获得的代码:
#include <iostream>
int main()
{
// int null = 0, *p = null; // it is not legal; depending on intent there are two ways to fix (that I can think off atm)
{
int null = 0, *p = &null; // if the goal is to point to 'null'
}
{
int null2 = 0, *p2 = 0; // if the goal is to create a nullptr
}
{
const int null3 = 0, *p3 = null3; // if the goal is to create a nullptr
}
{
constexpr int null4 = 0, *p4 = null4; // if the goal is to create a nullptr
}
return 0;
}
当我通过 Microsoft Visual Studio CMDPrompt 运行 时,它允许我 'cl "Exercise 2.32.cpp"' 没有错误。
0
是表示 空指针常量 的一种方式。 (它是一个计算结果为零的整数类型。)换句话说,它是一种特殊情况,您可以为其分配一个指针类型。
符合标准的编译器应该对指向 null3
和 null4
的指针类型分配发出诊断。 (它还应该为 int *p = +0;
发出诊断。)如果您没有,则检查是否设置了适当的编译器标志。
不过使用 nullptr
要好得多:
int *p = nullptr;
我正在完成 C++ Primer 中的练习,并找到了练习 2.32 的在线解决方案。
我了解到以下代码是非法的,因为初始化无法从 int 转换为 int*:
int null = 0, *p = null;
但是,我没有想到的两个提到的解决方案是:
const int null3 = 0, *p3 = null3;
constexpr int null4 = 0, *p4 = null4;
为什么在编译时允许这些没有错误?我仍然期望 p3 和 p4 的初始化需要 & 来表示地址 (&null3, &null4)。
这是我从记事本文件中获得的代码:
#include <iostream>
int main()
{
// int null = 0, *p = null; // it is not legal; depending on intent there are two ways to fix (that I can think off atm)
{
int null = 0, *p = &null; // if the goal is to point to 'null'
}
{
int null2 = 0, *p2 = 0; // if the goal is to create a nullptr
}
{
const int null3 = 0, *p3 = null3; // if the goal is to create a nullptr
}
{
constexpr int null4 = 0, *p4 = null4; // if the goal is to create a nullptr
}
return 0;
}
当我通过 Microsoft Visual Studio CMDPrompt 运行 时,它允许我 'cl "Exercise 2.32.cpp"' 没有错误。
0
是表示 空指针常量 的一种方式。 (它是一个计算结果为零的整数类型。)换句话说,它是一种特殊情况,您可以为其分配一个指针类型。
符合标准的编译器应该对指向 null3
和 null4
的指针类型分配发出诊断。 (它还应该为 int *p = +0;
发出诊断。)如果您没有,则检查是否设置了适当的编译器标志。
不过使用 nullptr
要好得多:
int *p = nullptr;