在课堂里:
class foo
{
public:
static int bar; //declaration of static data member
};
int foo::bar = 0; //definition of data member
Run Code Online (Sandbox Code Playgroud)
我们必须明确定义静态变量,否则会产生一个
undefined reference to 'foo::bar'
我的问题是:
请注意,这与先前提出的问题不重复undefined reference to static variable.这个问题打算问一下静态变量的明确定义背后的原因.
解决这个简单的问题后,我不得不问:
- >在类的H文件中,定义了一个const静态成员,例如:
class ex {
const static int my_ex;
};
Run Code Online (Sandbox Code Playgroud)
- >在CPP文件中指定值
ex::my_ex = 32;
Run Code Online (Sandbox Code Playgroud)
然后一个人得到错误"冲突的声明"(以及"不命名类型").我理解CPP文件中的定义也是一个声明,它确实会产生从链接器看到的冲突,但为什么只关于const说明符(和类型)而不是静态的?我只需要写
const int ex::my_ex = 32;
Run Code Online (Sandbox Code Playgroud)
让它编译.但不是静态的......为什么不呢?为什么我不能只定义和不重复声明相关的步骤(类型,特定标识符)?