C++ pointer to class

后端 未结 6 1676
小鲜肉
小鲜肉 2021-01-30 23:11

Can anyone tell me what the difference is between:

Display *disp = new Display();

and

Display *disp;
disp = new Display();
         


        
6条回答
  •  死守一世寂寞
    2021-01-30 23:59

    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.

提交回复
热议问题