[英]Initialize a Struct containing a const array with initializer list
I working with C++11 and have a Class containing the following Struct: 我使用C ++ 11并拥有一个包含以下结构的类:
struct Settings{
const std::string name;
const std::string* A;
const size_t a;
};
class X {
static const Settings s;
//More stuff
};
In the .cpp
file I want to define it like this 在
.cpp
文件中,我想像这样定义它
X::s = {"MyName", {"one","two","three"}, 3};
But this does not work. 但这不起作用。 However it does work using an intermediate variable
但是它确实可以使用中间变量
const std::string inter[] = {"one","two","three"};
X::s = {"MyName", inter, 3};
Is there a way to do it without the intermediate variable? 有没有办法在没有中间变量的情况下做到这一点?
A pointer cannot be initialized from a list of values. 无法从值列表初始化指针。 You could use
std::vector
instead: 您可以使用
std::vector
代替:
#include <vector>
struct Settings{
const std::string name;
const std::vector<std::string> A;
// ^^^^^^^^^^^^^^^^^^^^^^^^
const size_t a;
};
You can then write: 然后你可以写:
class X {
static const Settings s;
//More stuff
};
const Settings X::s = {"MyName", {"one","two","three"}, 3};
Here is a live example . 这是一个实例 。
As suggested by Praetorian in the comments , you may want to replace std::vector
with std::array
, if it is acceptable for you to specify the size of the container explicitly, and if the size does not need to change at run-time: 正如意见建议的执政官 ,你可能需要更换
std::vector
使用std::array
,如果它是可以接受的,你要明确指定容器的大小,如果大小不需要在运行-改变时间:
#include <array>
struct Settings{
const std::string name;
const std::array<std::string, 3> A;
// ^^^^^^^^^^^^^^^^^^^^^^^^^^
const size_t a;
};
And here is the live example . 这是现场的例子 。
That's because you're storing a pointer to an array of strings, not the strings themselves; 那是因为你要存储一个指向字符串数组的指针,而不是字符串本身; so you need an array of strings somewhere to point to.
所以你需要一个指向某个地方的字符串数组。 All you have is a brace-initialiser containing pointers to character arrays.
你所拥有的只是一个包含指向字符数组指针的大括号初始化程序。
If you were to store the strings themselves (in a vector<string>
, for example), then the first version would work. 如果你要自己存储字符串(例如,在
vector<string>
),那么第一个版本就可以了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.