【发布时间】:2021-12-28 00:23:09
【问题描述】:
我阅读了很多关键字“静态”的定义,但我仍然觉得它很混乱。这个程序的输出应该是:
1 2 1 2 3 4 1 1 2 3 4 8 7 6 5 1 2 6 5
我了解全局成员是如何调用的,但是当程序到达 main 和 static D d;我都糊涂了。提前感谢任何愿意解释的人!
#include <iostream>
using namespace std;
struct D {
D() { cout << "1" << endl; }
~D() { cout << "5" << endl; }
};
class C {
public:
D d;
C() { cout << "2" << endl; }
~C() { cout << "6" << endl; }
};
struct B {
C c;
B() { cout << "3" << endl; }
~B() { cout << "7" << endl; }
};
struct A {
B b;
A() { cout << "4" << endl; }
~A() { cout << "8" << endl; }
};
extern A a;
C c;
int main() {
static D d;
A{};
C{};
return 0;
}
A a;
extern B b;
【问题讨论】:
-
您的代码中没有全局成员。如果您认为有,那可能是您感到困惑的一个因素。
-
我对你的困惑感到困惑。你输入了你期望的输出,但是你得到了什么?
标签: c++ struct constructor static output