[英]C++ initializer list for std::vector<obj*> as constructor parameter
I have a situation where I need to create instances of a class with many object pointer parameters. 我遇到一种情况,需要创建带有许多对象指针参数的类的实例。 But, I'm looking for a simpler way. 但是,我正在寻找一种更简单的方法。 In this code sample, I demonstrate very generically what I'm trying to do. 在此代码示例中,我非常笼统地演示了我要执行的操作。
#include <vector>
#include <string>
class A
{
public:
A(std::string param);
};
class B
{
public:
B(std::vector<A*> params);
};
int main(int argc, char* argv[])
{
std::vector<A*> my_arguments;
my_arguments.push_back(new A("A1"));
my_arguments.push_back(new A("A2"));
my_arguments.push_back(new A("A3"));
my_arguments.push_back(new A("A4"));
B my_b = new B(my_arguments);
}
I don't like having to use an additional 5 lines to create the parameters for this call. 我不想使用额外的5行来创建此调用的参数。 Is there an alternate way to do this that requires less code. 是否有另一种方法来执行此操作,所需的代码更少。 I tried using an array like so, but it doesn't seem to be working: 我尝试使用像这样的数组,但是它似乎不起作用:
B my_b = new B([new A("A1"), new A("A2"), new A("A3"), new A("A4")]);
How could I achieve a similar result? 我如何获得类似的结果? I thought about using va_list
, but that would require another parameter marking the end, or a count of the number of variables. 我考虑过使用va_list
,但是那将需要另一个标记结束的参数或对变量数量的计数。 It might be what I end up doing, but, are there any other strategies out there? 这可能是我最终要做的,但是,还有其他策略吗?
You were nearly there... 你快到了...
B my_b{{new A("A1"), new A("A2"), new A("A3"), new A("A4")}};
Note: your code was trying to create B my_b
which is not a pointer, so you don't need to use new
. 注意:您的代码正在尝试创建不是指针的B my_b
,因此您无需使用new
。 The outer {
}
pair surround the argument to the constructor, the inner {
}
pair create a std::initializer_list
for the std::vector
constructor, so the values therein are used to construct the std::vector
argument. 外部{
}
对围绕构造函数的参数,内部{
}
对为std::vector
构造函数创建一个std::initializer_list
,因此其中的值用于构造std::vector
参数。
Note that this syntax has been supported since C++11 - some compilers needs command line arguments to enable support for the C++11 Standard, eg gcc -std=c++11 ...
. 请注意,自C ++ 11开始就支持此语法-一些编译器需要命令行参数来启用对C ++ 11标准的支持,例如gcc -std=c++11 ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.