gpt4 book ai didi

使用模板的 C++ 链表

转载 作者:太空狗 更新时间:2023-10-29 21:01:31 24 4
gpt4 key购买 nike

我有以下类(class):

typedef struct Listable
{
struct Listable *next;
struct Listable *prev;

// Lots of other class members not pertaining to the question excluded here
} Listable;

我像这样继承了它:

typedef struct Object : Listable
{
} Object;

问题是,当我做这样的事情时:

Object *node;
for (node = objectHead; node; node = node->next);

我收到“node = node->next”的错误,因为 node->next 是 Listable 类型,而 node 是 Object 类型。

我如何使用 Listable 基类中的模板来使 prev 和 next 指针将它们的类型更改为正在使用的类?

也许是这样的:

typedef struct Listable<T>
{
struct Listable<T> *next;
struct Listable<T> *prev;

// Lots of other class members not pertaining to the question excluded here
} Listable;

我像这样继承了它:

typedef struct Object : Listable<Object>
{
} Object;

我有 10 多年的 C 语言经验,但对模板等 C++ 功能还很陌生。所以我不确定我应该使用什么语法。

最佳答案

模板语法本身相当简单:

template <typename T>
struct Listable
{
T *next;
T *prev;

// Lots of other class members not pertaining to the question excluded here
};

所以,当它像这样被 Object 继承时:

struct Object : Listable<Object>
{
};

Object 将获得 nextprev 指针。

由于 Listable 正在管理指针,因此您需要注意 Rule of Three .也就是说,您必须考虑在销毁、复制构造和分配期间需要做什么,以便正确管理内存。

关于使用模板的 C++ 链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18070554/

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