C++ pointer to class

后端 未结 6 1607
小鲜肉
小鲜肉 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:43

    You have found four ways to write the same thing.

    Examples 1 (Display *disp…) and 3 (Display* disp…) are identical; the spacing around * does not matter. However, style 1 is often preferred, because:

    Display* disp1, disp2;
    

    actually means:

    Display *disp1, disp2;
    

    i.e., disp2 is not a pointer.

    Example two (splitting across two lines) has the same effect, and will probably be compiled to the same code. The fourth example, using initializer syntax, does the same thing as well.

    Note that if these were classes, not pointers, there could be a difference in behavior and speed.

提交回复
热议问题