C++ 类对象和指针

以 class A{}; 为例:

类对象:

类对象的创建方式如下:

  A a;    //调用default构造函数

  A a = A();  //调用构造函数A()

  A a();    //使用构造函数A()构造对象 a

类对象存储在栈中,在其生命周期结束后自动释放,创建的是一个局部的临时变量。

类对象通过  . 操作符调用其成员函数。

类对象不能使用多态,通过对象调用的函数一定是该类中定义的函数。

 

类指针:

类指针的创建使用new,然后在使用完成后通过delete显式释放申请的内存,例如:

  A* a = new A();  //使用构造函数A()构造,并将构造的对象的地址返回给指针a

通过new创建的对象存储在堆中,但是指针本身仍然是存储在栈中,通过new创建的对象在使用结束后不会自动回收,需要使用delete显示释放之前申请的内存。

类指针通过 -> 操作符调用其成员函数

使用类指针可以使用多态。

 

类对象的创建可以参考:https://stackoverflow.com/questions/49802012/different-ways-of-initializing-an-object-in-c

Entity ent1;

This statement (🠕) uses default constructor of class Entity.


Entity ent2();

This definition (🠕) will be treated by compiler as a function prototype if that's possible.


Entity ent3(1, 2);

User-defined constructor is invoked for ent3.

Entity ent4 = Entity();

This is a proper version of ent2 case. Default constructor is invoked as part of value initialization. Its form allows to avoid Most Vexing Parse - ambiguity solving principle which makes ent2 incorrect.

Entity ent5 = Entity(2, 3);

A version of ent3 case. User-defined constructor invoked as part of value initialization.

Your question is tagged as C++11, and C++11 allows uniform initialization syntax:

Entity ent12{};     // This is a legal alternative of ent2 case
Entity ent13{1, 2};
Entity ent14 = {};
Entity ent15 = Entity{2, 3};

Note that uniform initialization syntax has a caveat. E.g. this line

std::vector<int> v(10); 

declares a vector of 10 elements. But this one

std::vector<int> v{10};

declares a vector initialized with single element of type int with value 10. This happens because std::vector has a constructor with following signature defined:

vector( std::initializer_list<T> init, const Allocator& alloc = Allocator() );

 

posted @ 2020-12-17 16:53  adfas  阅读(796)  评论(0编辑  收藏  举报