【问题标题】:Member access into incomplete type error: Templatized struct C++成员访问不完整类型错误:Templatized struct C++
【发布时间】:2013-12-27 03:00:06
【问题描述】:

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;
}

【问题讨论】:

    标签: c++ templates struct


    【解决方案1】:
    • 首先,由于您要声明递归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>();
    

    【讨论】:

      【解决方案2】:

      treeNode 什么都不是——字面意思是不是一个东西——没有它的模板参数。

      你必须这样做:

      treeNode <int> * t;
      

      或类似的东西。

      【讨论】:

        【解决方案3】:

        除了您没有设置模板参数之外,您似乎打错了。而不是

        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;   
        };
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-05-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-11-13
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多