Sha*_*awn 7 c++ static initialization declaration
my_test.h
#ifndef MY_TEST
#define MY_TEST
struct obj {
int x;
int y;
};
class A {
private:
const static int a=100;
const static obj b;
};
const obj A::b={1,2};
#endif
Run Code Online (Sandbox Code Playgroud)
使用此头文件编译cpp时,'multiple definition of 'A::b'会发生错误.
A::a生产错误?(我不能写代码const static obj b={1,2}中class A)当我已经使用保护宏时为什么会出现这种情况?
标头防护仅防止在同一翻译单元中多次包含标头文件内容,而不能跨多个翻译单元。
为什么
A::a没有错误消息(我无法const static obj b={1,2}在中编写代码class A)
作为 const 文字类型的静态数据成员的特殊情况,编译器允许进行类内初始化。您的示例之一是类内初始化。
const A::b在包含标头的每个翻译单元中定义相同的符号名称,因此打破了单一定义规则。
您需要将定义移至唯一一个源 cpp 文件,以便仅定义一次。