首页 > 解决方案 > 这个编译器错误是什么意思 - C++中的“'='标记之前的声明中的限定ID”?

问题描述

我试图了解类中私有 const 的用法。我的理解是 private const 用于在类中使某些东西保持不变,而 static 则用于拥有一个副本。

最初,我的代码使用的是 pi,它的数据类型是浮点数。因此,我尝试将 float 更改为 int,因为我读到 const static 仅允许用于类中的 int 类型。

#include <iostream>
class MyExample
{

 private:
   static const int x;

};

int main(void)
{
  int const  MyExample::x = 3;

  std::cout<<"x value is "<<MyExample::x<<std::endl;

  return 0;
}

编译——

$g++ -std=c++14 test.cpp
test.cpp: In function ‘int main()’:
test.cpp:12:27: error: qualified-id in declaration before ‘=’ token
   int const  MyExample::x = 3;

我知道移动“int const MyExample::x = 3;”这一行 从 main() 到外部,如果我也删除私有,则删除错误。

标签: c++c++11c++14

解决方案


我有同样的问题,但是当我把静态成员初始化放在主函数之外时,问题就解决了,像这样:

int const  MyExample::x = 3;
int main(){...}

推荐阅读