[英]Why can't I assign an integer value to an integer pointer in C++?
My code is我的代码是
int null = 0;
int *p = null;
It gives me an error: cannot initialize a variable of type 'int *' with an lvalue of type 'int'.它给了我一个错误:无法用“int”类型的左值初始化“int *”类型的变量。
In C it would work.在 C 中它会起作用。
EDIT:编辑:
How can I make it work in this spirit?我怎样才能让它本着这种精神运作?
It's from an exercise (2.32) from the Primer C++ book:它来自 Primer C++ 书中的练习 (2.32):
Is the following code legal or not?以下代码是否合法? If not, how might you make it legal?
如果不是,你如何使它合法?
int null = 0, *p = null;
change int *p = null;
改变
int *p = null;
to int *p = (int*)null;
到
int *p = (int*)null;
If you are using C++11 then use nullptr
:如果您使用的是 C++11,则使用
nullptr
:
int *p = nullptr;
If you are not using C++11 then use NULL
instead:如果您不使用 C++11,请改用
NULL
:
int *p = NULL;
Do not define your own null
value at all, since C/C++ already has one of its own.根本不要定义你自己的
null
值,因为 C/C++ 已经有了它自己的null
值。 NULL
has no type, it is simply defined as 0
, and an integer literal 0
can be assigned to a pointer: NULL
没有类型,它被简单地定义为0
,并且可以将整数文字0
分配给指针:
int *p = 0;
You should use nullptr
in C++11.您应该在 C++11 中使用
nullptr
。 C++ doesn't do automatic conversion between int and x* (where x is type), so using an int
typed variable to define null won't work. C++ 不会在 int 和 x*(其中 x 是类型)之间进行自动转换,因此使用
int
类型变量来定义 null 将不起作用。 In pre-C++11, you can use integral literals, like 0
.在 C++11 之前的版本中,您可以使用整数文字,例如
0
。 (You can still use integral constants after the new standard, but there are good reasons for using nullptr
over NULL
. What are the advantages of using nullptr? ) (在新标准之后你仍然可以使用整数常量,但是使用
nullptr
不是NULL
有很好的理由。使用nullptr
有什么好处? )
You can read more about it nullptr
here: http://en.cppreference.com/w/cpp/language/nullptr .您可以在此处阅读有关
nullptr
更多信息: http : //en.cppreference.com/w/cpp/language/nullptr 。
我认为 *p 不是 C 的正确标识符。这是因为一个好的标识符不应该以符号开头,而应该以字母开头。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.