相关疑难解决方法(0)

h文件中的静态关键字和内部链接

还有一个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文件被包含两次,并且因为声明了 …

c++ static one-definition-rule linkage

14
推荐指数
1
解决办法
1066
查看次数

标签 统计

c++ ×1

linkage ×1

one-definition-rule ×1

static ×1