C++当类型T需要构造函数时,是否可以创建类型T的std::列表

C++ Is it possible to create a std::list of type T when a constructor is required for type T?

本文关键字:类型 创建 std 列表 构造函数 C++ 是否      更新时间:2023-10-16

例如:

class apple
{
public:
string name;
apple::apple(string name) : name(name)
{
}
};

如果我想列出一堆每个都有苹果类型的列表,我想我可以做std::list<apple> empire("empire"), macintosh("macintosh")之类的事情。基本上,我想在创建列表时为list<T>声明的类T的构造函数传递参数。很抱歉,如果我没有正确解释这一点,如果你有能力,请随时编辑我的问题。

谢谢

EDIT这个问题似乎令人困惑,可能是因为我举了一个不好的例子。我需要重新设计我的课根据这个例子,我想要的是一个所有帝国苹果的列表,该列表中的每个苹果都有一个指定类型的帝国,以及一个所有麦金托什苹果的列表。

因此,为了澄清一些或混淆更多,我们开始。

class apple
{
public:
string variety_name;
string description;
apple::apple(string variety_name, string description)
: variety_name(variety_name), description(description)
{
}
};
int _tmain(int argc, _TCHAR* argv[])
{
// Vlad from Moscow's answer
std::list<apple> empire(1, apple("empire", "picked yesterday")),
macintosh(1, apple( "macintosh", "picked yesterday")); 
// Vaughn Cato's answer
empire.push_back(apple("empire", "picked today"));
macintosh.push_back(apple("macintosh", "picked today"));
for(list<apple>::iterator it=empire.begin(); it != empire.end(); ++it)
{
cout << it->variety_name << " " << it->description << endl;
}
for(list<apple>::iterator it=macintosh.begin(); it != macintosh.end(); ++it)
{
cout << it->variety_name << " " << it->description << endl;
}
return 0;
}

因此,正如你所看到的,将品种储存一次比每次都容易;我的课显然需要重新设计,但这并没有降低答案的有效性。感谢大家的帮助

当然,您可以使用emplace()emplace_front()emplace_back()使用适当的构造函数在适当的位置构建对象:

std::list<apple> list;
list.emplace(list.end(), "one");
list.emplace_front("two");
list.emplace_back("three");

您可以进行

std::list<apple> a;
a.push_back(apple("delicious"));

在C++11中,您可以使用初始值设定项列表:

#include <list>
#include <string>
int main() {
// C++11 initializer-list
std::list<std::string> species = { "empire", "macintosh" };

// Without C++11: You may initialize with an array:
const char* species_array[] = { "empire", "macintosh" };
std::list<std::string> species_list(
species_array,
species_array + sizeof(species_array)/sizeof(species_array[0]));
return 0;
}

苹果是:

int main() {
// C++11 initializer-list
std::list<apple> species = { apple("empire"), apple("macintosh") };

// Without C++11: Initialize with an array:
const apple species_arry[] = { apple("empire"), apple("macintosh") };
std::list<apple> species_list(
species_arry,
species_arry + sizeof(species_arry)/sizeof(species_arry[0]));
return 0;
}

apple(string name);

是一个所谓的转换构造函数。它将std::string类型的对象转换为apple类型的对象。当编译器等待aoole类型的对象但得到std::string类型的对象时,它可以被隐式调用。

如果您将构造函数声明为显式,则无法执行此操作。例如

explicit apple(string name);

在这种情况下,您需要显式地指定构造函数。例如

std::list<apple> empire( 1, apple( "empire" ) );