我需要在多个源文件中使用一个结构,该结构是我的类的静态成员。这是一个精简的示例:
头文件
namespace NS {
class Foo {
public:
static struct Bar {
bool test = false;
uint32_t value; // uninitialized
} bar;
};
}
源文件1
#include "myHeader.hpp"
using namespace NS;
Foo::Bar Foo::bar;
/* the rest of my first source file */
在添加第二个源文件之前,这似乎没有任何问题。
源文件2
#include "myHeader.hpp"
using namespace NS;
Foo::Bar Foo::bar;
/* the rest of my second source file */
将结构添加到第二个源文件后,出现“多个定义”错误。有谁知道如何进行这项工作,以便可以在多个源文件中使用静态成员结构?
一个定义规则也适用于静态数据成员。应该只有形式的[[one定义
Foo::Bar Foo::bar;
您可以选择将其放置在哪个翻译单位(中。这与在给定的翻译单元中是否可以[[使用]]无关。为此,头文件中包含的.cpp
文件中,但必须将其放置在其中的正好一个
declaration
就足够了。