我想知道在构造函数中,当初始数组值是构造函数参数时,初始化类的std::array
成员的正确方式是什么?
更具体地说,考虑以下示例:
class Car {
public:
Car(const std::string& color, int age): color_(color), age_(age) {}
// ...
private:
std::string color_;
int age_;
};
class ThreeIdenticalCars {
private:
std::array<Car, 3> list;
public:
ThreeIdenticalCars(const std::string& color, int age):
// What to put here to initialize list to 3 identical Car(color,age) objects?
{}
};
显然一种方法是编写list({Car(color,age), Car(color,age), Car(color,age)})
,但如果我们想要30辆相同的汽车而不是三辆,这显然无法扩展。
如果我使用std::vector
而不是std::array
,解决方案将是list(3, Car(color,age)
(或list(30, Car(color, age))
),但由于在我的问题中列表的大小已知,因此我认为使用std:array
更正确。
std::vector
或std::array
都不是更正确或更错误的选择。每种方法都有其优缺点,你需要评估在每种情况下哪种方法更适用。 - Slava