簡體   English   中英

C ++中的靜態數據成員

[英]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的原因如下:

  1. B有型的靜態字段A (不是指針,一個真實的,生活,例如,類型A )。
  2. 因此, B任何用法都應要求對其進行一次靜態初始化。
  3. 因此,將需要初始化類型為A的靜態字段。
  4. 因此,調用A的構造函數即可。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM