c ++中的静态数据成员

时间:2017-08-26 19:17:05

标签: c++

#include <iostream>
using namespace std;

class A
{
    int x;
public:
    A() { cout << "A's constructor called " << endl; }
};

class B
{
    static A a;
public:
    B() { cout << "B's constructor called " << endl; }
    static A getA() { return a; }
};

A B::a; // definition of a

int main()
{
    B b1, b2, b3;
    A a = b1.getA();

    return 0;
}

输出:

A's constructor called 
B's constructor called 
B's constructor called 
B's constructor called 

这里即使A不是B的基类,为什么首先调用A&#39的构造函数?

1 个答案:

答案 0 :(得分:1)

为什么A的构造函数被称为一次 first ,作为代码的一部分,原因如下:

  1. B有一个类型为A的静态字段(不是指针,真实,实时,类型为A的实例)。
  2. 因此,B的任何使用都应该要求将其静态初始化一次
  3. 因此,需要初始化A类型的静态字段
  4. 因此,调用A的构造函数是为了这样做。