[英]Why static member can't be defined in headerfile with #pragma once
[英]Why can't a static member variable be defined inside main()?
class test
{
public:
static int i;
int func() {
return i;
}
};
int main()
{
test::i = 20;
}
无法使用clang: error: linker command failed with exit code 1 (use -v to see invocation)
。
如果我使 static 变量inline
,我可以在main
中定义它。 或者,如果我不使其内联,我可以在 class 声明和main()
之间定义它,如下所示:
class test
{
public:
static int i;
int func() {
return i;
}
};
int test::i = 20;
int main()
{
}
为什么这行得通而前者不行? 另外,为什么int
已经被声明为int
inside test
时这里还需要它?
在一个function里面,语句
test::i = 20;
是一个表达式(不是定义)。 它将值 20 存储到test::i
中。 但是如果test::i
从未被定义,你就不能在其中存储一个值。
另一方面,在命名空间 scope 处,当您编写
int test::i = 20;
这是test::i
的定义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.