c - 如何在C编程中删除以下结构体中具有成员函数的结构体?

标签 c struct binary-tree binary-search-tree

我能够创建下面的所有函数并执行所有操作,但我无法删除这棵树,所以请有人帮助我如何删除这种类型的结构

typedef struct Tree
{

Node *root;

Data *(*insert)(struct Tree *, Data);

Data *(*search)(struct Tree *bst, Data value);

void (*sort)(struct Tree *, Data *);

int (*compare)(struct Tree *t, struct Tree *copy);

struct Tree * (*clone)(struct Tree *t);

void (*delete)(struct Tree * bst);

void (*removeData)(struct Tree * bst, Data value);
}Tree;

树实例如下

Tree *newTree()
{

    Tree *bsttemp = (Tree *)malloc(sizeof(Tree));

    bsttemp->root = NULL;

    bsttemp->insert = &insert;

    bsttemp->search = &search;

    bsttemp->sort = &sort;

    bsttemp->compare = &compare;

    bsttemp->clone = &clone;

  //  bsttemp->delete = &delete;

    bsttemp->removeData = &removeData;

    return bsttemp;
}

最佳答案

将函数放入 C 结构体中至少是不常见的。由于 C 不会自动传递 this 指针,因此您必须使用类似

的东西
struct Tree *tree;
...
struct Tree *tree2 = tree->clone(tree);  // same as directly calling: clone(tree)

它通常仅用于实现虚拟函数,这意味着该函数可以依赖于对象,这是一个非常不常见的用例 - 它通常依赖于一个对象组,因此该对象只有一个指向 vTable 的指针,它是一种函数数组。

C 中的规则是:首先销毁成员,然后释放对象,所以这里 if 可以或多或少

void delete(Tree &tree) {
    // destroy and free descendants of root
    ...
    // destroy and free root
    ...
    free(tree);
}

关于c - 如何在C编程中删除以下结构体中具有成员函数的结构体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53662962/

相关文章:

c - 字数统计程序打印不同的计数

c - 纯油-C。我如何解释这个c结构

c - 没有标签的结构

c - 通过尾指针添加到链表,无需 3 级间接

haskell - zipWith 用于 Haskell 中的树

java - 设置父节点

c - OpenSSL 代码问题

c++ - 将星号放在名称之前的指针中是典型的编程实践吗?

c - 如何检查 openssl 或 cryptopp 是否安装并使用系统中实际存在的库(已安装)?

r - 是否可以使用 R 获得分类树分析中节点的 p 值?