gpt4 book ai didi

c++ - 我可以用花括号构造一个链表吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:44:18 25 4
gpt4 key购买 nike

我是面向对象的 C++ 的新手,我正在尝试以这种方式为链表创建构造函数:

在 List.h 的某处我们会有这样的:

struct Node
{
int data;
Node *next;
};

然后在 main.cpp 中,我希望能够构建这样的列表:

int main()
{
List A({1,2,3,4,5,6});// I want the amount of numbers to indicate the size of
//the list and the numbers to go into each node in order
return 0;
}

所以我的问题是,我可以制作这样的构造函数吗?如果是这样,那又如何?我必须使用模板来做这个吗?我试图在 SO 中找到这样的问题,但它们都包含模板,我还没有学到。如果我可以让我的构造函数执行此操作,是否可以在不使用模板的情况下执行此操作?

最佳答案

是的,你可以做到这一点(使用 C++11)。

你需要定义一个接受 std::initializer_list<int> 的构造函数.(是的,这是一个模板,但我将向您展示如何使用它。:-))

std::intitializer_list<int> 的可能实现-构造函数可能如下所示:

//in class List:
List (std::initializer_list<int> init) {
for (auto v : init)
this->emplace_back(v);
}

你必须在哪里实现 emplace_back自己作为一种锻炼。 emplace_back应该构建一个新的 Node并将其附加到 List .这将是一个有用的成员函数(我保证)。

可能不重要的通知:如果emplace_back做堆分配,这段代码可能会泄漏。在这种情况下,委托(delegate)给一个构造函数来放置 List进入有效状态,因此析构函数可以释放所有堆分配的 Nodes .如果您不了解这一点,那么它对您的应用程序来说很可能不是太重要。

关于c++ - 我可以用花括号构造一个链表吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22702221/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com