将构造函数的参数分配给向量变量

Assigning constructor's argument to the vector variable

本文关键字:向量 变量 分配 参数 构造函数      更新时间:2023-10-16

我有这个代码:

class Entry
{
protected :
    string itemName;
    vector<string> allItems;
public :
    Entry(string item) : allItems(item){};
}

我想使用push_back()将构造函数参数添加到向量变量allItems中。我该怎么做:

Entry("My Entry Name");

然后将变量My Entry Name添加到<vector>

考虑使用列表初始化:

Entry(string item) : allItems({ item }){};

在C++11中,您可以从初始值设定项列表构建:

Entry(std::string item) : allItems({std::move(item)}){};

在这种情况下,您也可以只使用C++98并使用填充构造函数,但只使用1个元素进行填充:

Entry(const std::string& item) : allItems(1, item){};