繁体   English   中英

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

[英]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"}
    })

    {
    }
};

主要错误在您的基类中,因为原始数组不能通过值传递。 只需使用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" } )
    {
    }
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM