📜  什么时候调用构造函数?

📅  最后修改于: 2021-05-30 15:39:54             🧑  作者: Mango

构造函数何时需要调用不同类型的对象,例如全局,局部,静态局部,动态?

1)全局对象:对于全局对象,在调用main()之前先调用构造函数。例如,请参见以下程序和输出:

#include
using namespace std;
  
class Test
{
public:
  Test();
};
  
Test::Test()  {
    cout << "Constructor Called \n";
}
  
Test t1;
  
int main() {
    cout << "main() started\n";
    return 0;
}
/* OUTPUT:
      Constructor Called 
      main() started
*/

2)函数或块作用域(自动变量和常量)对于非静态本地对象,当执行到达声明对象的位置时,将调用构造函数。例如,请参见以下程序和输出:

using namespace std;
  
class Test
{
public:
  Test();
};
  
Test::Test()  {
    cout << "Constructor Called \n";
}
  
void fun() {
  Test t1;
}
  
int main() {
    cout << "Before fun() called\n";
    fun();
    cout << "After fun() called\n";
    return 0;
}
/* OUTPUT:
       Before fun() called
       Constructor Called
       After fun() called
*/

对于本地静态对象,一次(并且只有第一次)执行到达声明对象的位置。例如,以下程序的输出是:

#include
using namespace std;
  
class Test
{
public:
  Test();
};
  
Test::Test()  {
    cout << "Constructor Called \n";
}
  
void fun() {
  static Test t1;
}
  
int main() {
    cout << "Before fun() called\n";
    fun();
    cout << "After fun() called\n";
    fun();  //constructor is not called this time.
    return 0;
}
/* OUTPUT
       Before fun() called
       Constructor Called
       After fun() called
*/

3)类范围:创建对象时,编译器确保调用其所有子对象(其成员和继承的对象)的构造函数。如果成员具有默认构造函数或不带参数的构造函数,则将自动调用这些构造函数,否则可以使用“初始化列表”来调用参数化的构造函数。例如,请参阅程序1和程序2及其输出。

// PROGRAM 1: Constrcuctor without any parameter
#include
using namespace std;
  
class A
{
public:
  A();
};
  
A::A() {
    cout << "A's Constructor Called \n";
}
  
class B
{
  A t1;
public:
  B();
};
  
B::B() {
    cout << "B's Constructor Called \n";
}
  
int main() {
    B b;
    return 0;
}
/* OUTPUT:
      A's Constructor Called
      B's Constructor Called
*/
// PROGRAM 2: Constrcuctor with parameter (using initializer list)
#include 
using namespace std;
  
class A
{
public:
    int i;
    A(int );
};
  
A::A(int arg)
{
    i = arg;
    cout << "A's Constructor called: Value of i: " << i << endl;
}
  
// Class B contains object of A
class B
{
    A a;
public:
    B(int );
};
  
B::B(int x):a(x)
{
    cout << "B's Constructor called";
}
  
int main()
{
    B obj(10);
    return 0;
}
/* OUTPUT
       A's Constructor called: Value of i: 10
       B's Constructor called
*/

4)动态对象:对于动态分配的对象,构造函数由new运算符调用。例如,请参见以下程序和输出。

#include
  
using namespace std;
  
class Test
{
public:
  Test();
};
  
Test::Test()  {
    cout << "Constructor Called \n";
}
  
int main()
{
    cout << "Before new called\n";
    Test *t1 = new Test;
    cout << "After new called\n";
    return 0;
}
/* OUTPUT
      Before new called
      Constructor Called
      After new called
*/

参考:
http://web.cs.wpi.edu/~cs2303/c10/Protected/Lectures-C10/Week5_MoreClasses.ppt

要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”