问题描述
我在一本书中见过运动,但我无法弄清楚答案:
I'va seen an excersise in a book, but I cannot figure out the answer:
int null = 0,* p = null;
当然,第二个不合法,您不能将int转换为int *。
Of course, the second one is not legal, you cannot convert int to int*.
主题位于 constexpr
部分。
GUYS!这只是关于指针,const和constexprs的练习!我认为,您必须在没有强制转换和nullptr的情况下解决它。
推荐答案
在C ++ 11中,为null指针常量定义为
In C++11, a null pointer constant was defined as
(C ++ 11 [conv.ptr] 4.10 / 1)
(C++11 [conv.ptr] 4.10/1)
这意味着添加 constexpr
到声明实际上使 null
成为有效的空指针常量:
This means that adding constexpr
to the declaration actually makes null
a valid null pointer constant:
constexpr int null = 0, *p = null;
请注意,这被视为缺陷,在C ++ 14中已更改,因此只有整数 literal 可以是空指针常量:
Note that this was considered a defect and changed in C++14, so that only an integer literal can be a null pointer constant:
(C ++ 14 N4140 [conv.ptr] 4.10 / 1)
(C++14 N4140 [conv.ptr] 4.10/1)
因此,有一种方法可以在C ++ 11中使用 constexpr
使初始化合法化,但它的存在被认为是标准缺陷。并在C ++ 14中删除。因此,这本书正在教授过时的信息。
So, there is a way to make the initialisation legal using constexpr
in C++11, but its existence was considered a standard defect and removed in C++14. The book is therefore teaching outdated information.
请注意,由于这是一个缺陷,因此编译器通常也将此行为移植到其C ++ 11模式(如果他们甚至首先实现了原始代码。
Note that because this is a defect, compilers have generally backported this behaviour to their C++11 mode as well (if they even implemented the original one in the first place).
这篇关于如何在C ++中使此初始化合法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!