指向类的C ++指针 [英] C++ pointer to class
问题描述
谁能告诉我两者之间的区别是什么
Display *disp = new Display();
和
Display *disp;
disp = new Display();
和
Display* disp = new Display();
和
Display* disp(new Display());
第一种情况:
Display *disp = new Display();
做三件事:
- 它将创建一个新的变量
disp
,其类型为Display*
,即,指向类型为Display
的对象的指针,然后 - 它在堆上分配一个新的
Display
对象,并且 - 它将
disp
变量设置为指向新的Display
对象.
在第二种情况下:
Display *disp; disp = new GzDisplay();
您创建类型为Display*
的变量disp
,然后在堆上创建类型为 的对象 GzDisplay
,并将其指针分配给disp
变量.
这仅在GzDisplay是Display的子类时才有效.在这种情况下,它看起来是多态的示例. /p>
另外,为了发表您的评论,声明之间没有区别:
Display* disp;
和
Display *disp;
但是,由于C类型规则的工作方式,两者之间存在差异:
Display *disp1;
Display* disp2;
和
Display *disp1, disp2;
因为在最后一种情况下,disp1
是指向Display
对象的指针,该对象可能分配在堆上,而disp2
是实际的对象,可能分配在堆栈上.也就是说,虽然指针可以说是类型的一部分,但解析器会将其与变量关联.
Can anyone tell me what the difference is between:
Display *disp = new Display();
and
Display *disp;
disp = new Display();
and
Display* disp = new Display();
and
Display* disp(new Display());
The first case:
Display *disp = new Display();
Does three things:
- It creates a new variable
disp
, with the typeDisplay*
, that is, a pointer to an object of typeDisplay
, and then - It allocates a new
Display
object on the heap, and - It sets the
disp
variable to point to the newDisplay
object.
In the second case:
Display *disp; disp = new GzDisplay();
You create a variable disp
with type Display*
, and then create an object of a different type, GzDisplay
, on the heap, and assign its pointer to the disp
variable.
This will only work if GzDisplay is a subclass of Display. In this case, it looks like an example of polymorphism.
Also, to address your comment, there is no difference between the declarations:
Display* disp;
and
Display *disp;
However, because of the way C type rules work, there is a difference between:
Display *disp1;
Display* disp2;
and
Display *disp1, disp2;
Because in that last case disp1
is a pointer to a Display
object, probably allocated on the heap, while disp2
is an actual object, probably allocated on the stack. That is, while the pointer is arguably part of the type, the parser will associate it with the variable instead.
这篇关于指向类的C ++指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!