指向类的C ++指针 [英] C++ pointer to class

查看:112
本文介绍了指向类的C ++指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能告诉我两者之间的区别是什么

Display *disp = new Display();

Display *disp;
disp = new Display();

Display* disp = new Display();

Display* disp(new Display());

解决方案

第一种情况:

Display *disp = new Display();

做三件事:

  1. 它将创建一个新的变量disp,其类型为Display*,即,指向类型为Display的对象的指针,然后
  2. 它在堆上分配一个新的Display对象,并且
  3. 它将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:

  1. It creates a new variable disp, with the type Display*, that is, a pointer to an object of type Display, and then
  2. It allocates a new Display object on the heap, and
  3. It sets the disp variable to point to the new Display 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆