c++ - 使用派生类的初始化列表初始化父类(super class)中类型数组的成员

标签 c++ inheritance initialization-list

如何初始化属于父类(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/

相关文章:

c++ - 如何创建一个仅在其类型具有特定成员函数时才编译的类?

c++ - 错误 : Invalid use of incomplete type

c++ - 如何在构造函数初始化列表中进行深层复制。 C++

c++ - C++ 构造函数中参数的默认值

c++ - 如何在 C++ Builder 中从 TADOQuery 扩展一个类?

c++ - C++何时查找初始化列表

c++ - 对 C++ 基类的模糊函数调用

c++ - 常量和全局

c++ - 从私有(private)成员值类型 (bool) 读取的 VC++ 访问冲突

Java 继承层次结构——实现父类(super class)正在实现的接口(interface)