还有一个static问题.我看过以下内容:
我仍然无法理解以下行为:我有一个h文件:
// StaticTest.h
#include <stdio.h>
static int counter = 0;
struct A {
A () {
counter++;
printf("In A's ctor(%d)\n", counter);
}
~A () {
counter--;
printf("In A's dtor(%d)\n", counter);
}
};
static A a;
Run Code Online (Sandbox Code Playgroud)
还有两个cpp文件:
// StaticTest1.cpp
#include "StaticTest.h"
int main () {
return 0;
}
Run Code Online (Sandbox Code Playgroud)
和:
// StaticTest2.cpp
#include "StaticTest.h"
Run Code Online (Sandbox Code Playgroud)
该计划的输出是:
In A's ctor(1)
In A's ctor(2)
In A's dtor(1)
In A's dtor(0)
Run Code Online (Sandbox Code Playgroud)
现在,A构造函数被调用两次,因为h文件被包含两次,并且因为声明了 …