c++ - struct 中的 std::vector 定义

标签 c++ vector std

<分区>

我定义了一个结构如下。

extern int x;
a = 1;
b = 2;
x = a*b;
struct  bStruct
{
    unsigned long   Cycles;                     
    unsigned long   Time;                                           
    std::vector<unsigned long> Chunks(x);
};

但是 Chunks 定义中的 x 被标记为错误,下方有一条红线。

错误信息是:

variable "x" is not a type name.

为什么会发生此错误,我该如何解决?

最佳答案

你的编译器认为 Chunks 是一个函数,像这样解析它:

std::vector<unsigned long> Chunks( x );
            |               |      |
            |               |      +---Wait a sec huh ? what type is 'x' ?? 
            |               |
            |               +---------Function name Chunks
            +----------Return Type std::vector<unsigned long>

您希望 Chunks 成为一个 data 成员,您需要使用以下方法对其进行初始化:

struct bStruct
{
    unsigned long Cycles;                     
    unsigned long Time;                                           
    std::vector<unsigned long> Chunks;

    bStruct() : Chunks(x)
    {
      // Constructor
    }
};

关于c++ - struct 中的 std::vector 定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26626643/

相关文章:

c++ - 包装 std::ignore

c++ - memcpy 与 startIndex?

C++ - 删除二维数组

c++ - 在 C++ 中使用 vector 数组的 vector

c++ - 为什么编译器会在模板函数上产生错误

C++11 在 int x, int y 之间随机,不包括 list<int>

c++ - 当我在 .cpp 文件中复制#include 时会发生什么

c++ - 深拷贝int数组c++

python - 可视化高维场箭头?

c++ - g++ 坚持使用 std::string 而不是 string