无法在 c++ 中初始化静态向量



我想初始化类中的向量Stack,如下所示。该向量将仅初始化一次,并且永远不会更新。

#ifndef X_HPP
#define X_HPP
#include <vector>
class Test
{
   public:
      void gen(double x);
      void PopStack();
   private:
         static std::vector<double> Stack;
};
#endif

CPP文件如下:

#include "X.hpp"
int main() {
    std::vector<double> Test::Stack = {1,2,3};
    //{1,2,3} is for representation. In the code, it is generated on the fly and is not a constant seq.
    Test t;
}

使用以下命令编译:

g++ -std=c++11 Y.cpp

报告的错误:

Y.cpp: In function ‘int main()’:
Y.cpp:4:37: error: qualified-id in declaration before ‘=’ token
     std::vector<double> Test::Stack = {1,2,3};

基本上,你应该移动这一行:

std::vector<double> Test::Stack = {1,2,3};

函数:

std::vector<double> Test::Stack = {1,2,3};
int main() {
    // ...
    return 0;
}

如果矢量是动态填充的,则可以将其更改为:

std::vector<double> Test::Stack;
int main() {
    // ...
    return 0;
}

并以某种方式在运行时填充堆栈

您不能初始化函数体内的静态成员变量(在您的情况下为 main(

通常,您将这种代码放在一个且唯一的 cpp 文件中,在任何方法的主体之外。像这样:

std::vector<double> Test::Stack = {1,2,3};
int main() {
    //{1,2,3} is for representation. In the code, it is generated on the fly and is not a constant seq.
    Test t;
}

最新更新