繁体   English   中英

成员访问不完整类型错误:模板化结构C ++

[英]Member access into incomplete type error: Templatized struct C++

对C ++来说很新,我第一次尝试模板。 我创建了一个struct, treeNode ,有左,右和父指针。 我希望树能够存储多种数据类型,因此我正在使用模板。 每当我尝试在.cpp文件中创建结构的实例,然后使用它来访问树的左/右指针时,我会收到此错误:成员访问不完整类型struct'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类)

由于您希望拥有通用树,因此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>();

没有它的模板参数, treeNode什么都不是 - 字面上不是一件事

你必须这样做:

treeNode <int> * t;

或类似的东西。

除此之外你没有设置模板参数,似乎你写了一个错字。 代替

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

应该

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM