[英]Static data member in 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的構造函數?
為什么在代碼中首先調用一次 A的構造函數,然后首先調用A的原因如下:
B
有型的靜態字段A
(不是指針,一個真實的,生活,例如,類型A
)。 B
任何用法都應要求對其進行一次靜態初始化。 A
的靜態字段。 A
的構造函數即可。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.