#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的构造函数?
发布于 2017-08-26 19:32:49
作为代码的一部分,只调用一次A的构造函数的原因如下:
B有一个A类型的静态字段(不是指针、真实的、活动的、A类型的实例)。B的使用都需要静态初始化一次。A类型的静态字段。A的构造函数就是为了做到这一点。https://stackoverflow.com/questions/45898872
复制相似问题