初始化C++中的向量类成员
问题描述:
我试图设置长度并启动类的向量成员。但它似乎是唯一可能的,如果初始化线是在课外。 你喜欢什么? (感谢)初始化C++中的向量类成员
//a vector, out of class set size to 5. initilized each value to Zero
vector<double> vec(5,0.0f);//its ok
class Bird{
public:
int id;
//attempt to init is not possible if a vector a class of member
vector<double> vec_(5, 0.0f);//error: expected a type specifier
}
答
class Bird{
public:
int id;
vector<double> vec_;
Bird(int pId):id(pId), vec_(5, 0.0f)
{
}
}
这也是初始化缺少你宁愿在构造函数体执行之前构建一个默认的构造函数和其他任何基类有用。
答
如果您使用C++ 11或更高版本,您应该阅读http://en.cppreference.com/w/cpp/language/data_members。对于C++ 98/03,@ user4581301的答案是最好的方法。
在C++ 11中,您可以拥有默认的成员值,但不能在C++ 98中使用。语法是'vector vec_ = vector (5,0.0f);' –
Franck