使用派生 class 的初始化列表初始化 superclass 中类型数组的成员

Initializing a member of type array in a superclass, using the initialization list of a derived 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"}
    })

    {
    }
};

主要错误在你的基础class,因为原始数组不能按值传递。只需使用 std::array 即可获得适当的值语义。

在您派生的 class 中,花括号太多了。你不需要内在的。

这是一个固定版本(我也删除了似乎与问题完全无关的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" } )
    {
    }
};