如何初始化属于父类(super class)的数组?我想在子类的初始化列表中设置父类(super class)数组的所有值。
struct Foo
{
std::string arr_[3];
Foo(std::string arr[3])
:arr_(arr)
{
}
};
class PersonEntity : public Foo
{
public:
PersonEntity(Person person)
:Foo(
{
{"any string"},
{"any string"},
{"any string"}
})
{
}
};
最佳答案
主要错误在您的基类中,因为原始数组不能按值传递。只需使用 std::array
即可获得适当的值语义。
在你的派生类中,花括号太多了。你不需要内部的。
这是一个固定版本(我还删除了似乎与问题完全无关的 Person
参数):
#include <array>
#include <string>
struct Foo
{
std::array<std::string, 3> arr;
Foo(std::array<std::string, 3> const& arr) : arr(arr)
{
}
};
class PersonEntity : public Foo
{
public:
PersonEntity()
: Foo( { "any string", "any string", "any string" } )
{
}
};
关于c++ - 使用派生类的初始化列表初始化父类(super class)中类型数组的成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35251576/