gpt4 book ai didi

c++ - 成员访问不完整类型错误: Templatized struct C++

转载 作者:行者123 更新时间:2023-11-28 03:01:17 24 4
gpt4 key购买 nike

C++ 的新手,第一次尝试使用模板。我创建了一个结构,treeNode,具有左指针、右指针和父指针。我希望树能够存储多种数据类型,因此我正在使用模板。每当我尝试在 .cpp 文件中创建结构的实例,然后使用它来访问树的左/右指针时,我都会收到此错误:成员访问不完整类型结构“treeNode”。知道我缺少什么吗?

这是 .h 文件中的代码(结构定义):

template <class T>
struct treeNode {
node<T> *l;
node<T> *r;
node<T> *p;
};

这是我在 .cpp 文件中的尝试:

#include "RedBlack.h"

struct treeNode* t;

Tree::Tree() {
t->l = NULL;
}

最佳答案

  • 首先,由于您声明的是递归 struct,因此成员的类型应与 struct 本身相同。
  • 第二件事:模板不像 Java 中的泛型。在您将类型变量替换为真实类型之前,它们不会提供真正可用的实现,因此您必须始终专门使用它们,或者通过在另一个模板上下文(例如 Tree)中保持某些类型变量仍然未被选择> 下面的类(class))

既然你想要一个通用的树,那么 Tree 类也应该是通用的:

template <class T>
struct node {
node<T> *l;
node<T> *r;
node<T> *p;
};

template <class T>
class Tree
{
private:
node<T> *root;

public:
Tree() : root(nullptr) { }
};

Tree<int> *tree = new Tree<int>();

关于c++ - 成员访问不完整类型错误: Templatized struct C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20789406/

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