Zee*_*ang 19 c++ initialization
谁能告诉我两者之间的区别是什么:
Display *disp = new Display();
Run Code Online (Sandbox Code Playgroud)
和
Display *disp;
disp = new Display();
Run Code Online (Sandbox Code Playgroud)
和
Display* disp = new Display();
Run Code Online (Sandbox Code Playgroud)
和
Display* disp(new Display());
Run Code Online (Sandbox Code Playgroud)
Dan*_*den 19
第一种情况:
Display *disp = new Display();
Run Code Online (Sandbox Code Playgroud)
有三件事:
disp带有类型的新变量,Display*即指向类型对象的指针Display,然后Display在堆上分配一个新对象,和disp变量设置为指向新Display对象.在第二种情况:
Display *disp; disp = new GzDisplay();
Run Code Online (Sandbox Code Playgroud)
创建的变量disp类型Display*,然后创建的对象不同的类型,GzDisplay,在堆上,和它的指针分配给disp变量.
这仅在GzDisplay是Display的子类时才有效.在这种情况下,它看起来像多态的一个例子.
另外,为了解决您的评论,声明之间没有区别:
Display* disp;
Run Code Online (Sandbox Code Playgroud)
和
Display *disp;
Run Code Online (Sandbox Code Playgroud)
但是,由于C类型规则的工作方式,因此存在以下区别:
Display *disp1;
Display* disp2;
Run Code Online (Sandbox Code Playgroud)
和
Display *disp1, disp2;
Run Code Online (Sandbox Code Playgroud)
因为在后一种情况下disp1是指向一个Display对象,可能是在堆上分配的,同时disp2是一个实际的对象,可能是在堆栈上分配.也就是说,虽然指针可以说是类型的一部分,但解析器会将其与变量相关联.
// implicit form
// 1) creates Display instance on the heap (allocates memory and call constructor with no arguments)
// 2) creates disp variable on the stack initialized with pointer to Display's instance
Display *disp = new Display();
// explicit form
// 1) creates Display instance on the heap (allocates memory and call constructor with no arguments)
// 2) creates disp variable on the stack initialized with pointer to Display's instance
Display* disp(new Display());
// 1) creates uninitialized disp variable on the stack
// 2) creates Display instance on the heap (allocates memory and call constructor with no arguments)
// 3) assigns disp with pointer to Display's instance
Display *disp;
disp = new Display();
Run Code Online (Sandbox Code Playgroud)
只有具有构造函数的复杂类型才能看到显式和隐式初始化形式之间的区别.对于指针类型(Display*),没有区别.
要查看显式和隐式表单之间的区别,请查看以下示例:
#include <iostream>
class sss
{
public:
explicit sss( int ) { std::cout << "int" << std::endl; };
sss( double ) { std::cout << "double" << std::endl; };
// Do not write such classes. It is here only for teaching purposes.
};
int main()
{
sss ddd( 7 ); // prints int
sss xxx = 7; // prints double, because constructor with int is not accessible in implicit form
return 0;
}
Run Code Online (Sandbox Code Playgroud)