繁体   English   中英

为什么不能在main()里面定义一个static的成员变量?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM