在列表中初始化类对象的数组

时间:2015-11-17 07:58:06

标签: c++ initializer-list

Car是一个模板类,其构造函数定义如下:

template <class carObject>
explicit Car( const carObject & notFound, int size = 101 );
Car( const carObject & rhs )

在我的标题文件(h)中,我有:

class Storage{
public:
    Storage();
    Car <char*> myCars[12];
};

在我的CPP文件(.cpp)中,我正在尝试使用初始化列表初始化myCars数组,如下所示:

Storage::Storage()
: myCars("notFound", 20)
{ //my other stuff}

但我不断收到错误消息:

error: invalid initializer for array member Car:myCars("notFound", 20)

任何帮助?

1 个答案:

答案 0 :(得分:2)

您的阵列需要12个初始化器,如

<强> Live On Coliru

template <typename T> struct Car {
    template <class carObject> explicit Car(const carObject &notFound, int size = 101) {}
};

struct Storage {
    Storage()
            : myCars{
                  Car<char *>{ "notFound", 20 }, Car<char *>{ "notFound", 20 }, Car<char *>{ "notFound", 20 },
                  Car<char *>{ "notFound", 20 }, Car<char *>{ "notFound", 20 }, Car<char *>{ "notFound", 20 },
                  Car<char *>{ "notFound", 20 }, Car<char *>{ "notFound", 20 }, Car<char *>{ "notFound", 20 },
                  Car<char *>{ "notFound", 20 }, Car<char *>{ "notFound", 20 }, Car<char *>{ "notFound", 20 },
              } {}
    Car<char *> myCars[12];
};

int main(){}

当然,如果元素类型是默认构造的,你可以省略一些初始化器。但初始化程序的结构需要匹配此结构