因此,我知道在C ++中,如果静态成员是const文字类型,则可以在类内部对其进行初始化,如下所示:
class test{
public:
static constexpr int stc = 1;
private:
int a = 0;
int b = 0;
int c = 0;
};
Run Code Online (Sandbox Code Playgroud)
静态constexpr变量stc可以用在编译器可以直接替换成员值的地方,即
int main () {int array[test::stc];}
Run Code Online (Sandbox Code Playgroud)
但是,如果在不能由编译器直接替换值的上下文中使用:
int main() { const int &cs = test::stc; }
Run Code Online (Sandbox Code Playgroud)
然后编译器(c)生成一个错误
c++ -std=c++11 -pedantic t.cpp -o t
Undefined symbols for architecture x86_64:
"test::stc", referenced from:
_main in t-a8ee2a.o
ld: symbol(s) not found for architecture x86_64
Run Code Online (Sandbox Code Playgroud)
除非静态成员是在类外部定义的,例如:
constexpr int test::stc;
为什么会这样呢?