繁体   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