我们可以说构造函数创建对象吗?

Can we say Constructor Creates Objects?

有人告诉我构造函数创建对象。但是在互联网上我搜索了对象创建时执行的构造函数。你能解释一下吗?我是 C++ 新手

In C++ a constructor is a special kind of class member function that is executed when an object of that class is instantiated.

Constructors are typically used to initialize member variables of the class to appropriate default values, or to allow the user to easily initialize those member variables to whatever values are desired.

所以当你调用构造函数时你有一个已经实例化的对象,所以构造函数不创建对象,也不创建对象变量,它只是用于初始化该对象内的变量(或使一些在使用对象之前要执行的任务)。

编辑:另外:

A constructor performs its work in this order:

  1. It calls base class and member constructors in the order of declaration.
  2. If the class is derived from virtual base classes, it initializes the object's virtual base pointers.
  3. If the class has or inherits virtual functions, it initializes the object's virtual function pointers. Virtual function pointers point to the class's virtual function table to enable correct binding of virtual function calls to code.
  4. It executes any code in its function body.

查看这些链接以获取更多信息:

http://www.learncpp.com/cpp-tutorial/85-constructors/

https://msdn.microsoft.com/en-us/library/s16xw1a8.aspx

https://isocpp.org/wiki/faq/ctors

class a{int a = 0;int b = 0;} a obj = new a(); 在上面的代码中 您的 obj 已创建,obj 的内存分配在堆栈中,然后是构造函数 代码正在执行