标头中的 std::vector 大小 [英] std::vector size in header
问题描述
我有一个关于 std::vector 的小问题.在 main.h 中,我尝试制作固定大小的 int 向量
I have small question about std::vector. In main.h i try to make fixed size int vector
std::vector<int> foo(7);
但是 g++ 给出了这个错误:
But g++ gived this error:
../test/main.h:21:26: error: expected identifier before numeric constant
std::vector<int> foo(7);
../main/main.h:21:26: error: expected ',' or '...' before numeric constant
如何创建固定大小长度的私有向量变量?或者我应该简单地在构造函数中制作
How can i create private vector variable of fixed size length? Or should i simply make in constructor
for(int i=0; i<7;i++){
foo.push_back(0);
}
推荐答案
假设 foo
是数据成员,您的语法无效.通常,您可以像这样初始化 T 类型的数据成员:
Assuming foo
is a data member, your syntax is invalid. In general, you can initialize a data member of type T like this:
T foo{ctor_args};
或者这个
T foo = T(ctor_args);
然而,std::vector
有一个接受 std::initializer_list
的构造函数,这意味着第一种形式将产生一个大小-1 向量,单个元素值为 7.所以你被困在第二种形式中:
However, std::vector<int>
has a constructor that takes an std::initializer_list<int>
, which means that the first form would yield a size-1 vector with a single element of value 7. So you are stuck with the second form:
std::vector<int> foo = std::vector<int>(7);
如果您坚持使用 C++11 之前的编译器,则需要使用构造函数:
If you are stuck with a pre-C++11 compiler, you would need to use a constructor:
class bar
{
public:
bar() : foo(7) {}
private:
std::vector<int> foo;
};
并注意在所有构造函数中初始化向量(如果适用).
and take care to initialize the vector in all constructors (if applicable.)
这篇关于标头中的 std::vector 大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!