在结构

时间:2017-03-15 04:08:00

标签: c++ templates struct typedef

我正在努力了解有关C ++的更多信息。这次是模板化课程。我正在尝试使用模板化数据类型构建链接列表类(是的,我知道std :: list)。我遇到的问题涉及嵌套结构的前向声明。我要做的是有一个封装模板类,其中底层实现是什么,在这种情况下是使用struct的传统链表。这是一些代码:

/*

Linked List Class Library

Requires C++ 2011


*/


#include <stdlib.h>
#include "ctypesx.h"


#ifndef __CUSTOM_HEADER_FILE__LINKLIST_H__
#define __CUSTOM_HEADER_FILE__LINKLIST_H__



template <typename T> class linklist_c
  {
    private:
      typedef struct linklist_node_tag llnode_t;
      struct linklist_node_tag
        {
          llnode_t *next;
          llnode_t *prev;
          uint64 idx;
          uint32 key;
          void *data;
        };
      llnode_t *head;
      llnode_t *tail;
      llnode_t *curr;
      uint32 count;
      uint32 maxitem;
      uint64 nidx;
    public:
      // Constructors & Destructors

      linklist_c()
        {
          this->head = NULL;
          this->tail = NULL;
          this->curr = NULL;
          this->count = 0;
          this->maxitem = -1;
          this->nidx = 0;
        }

      linklist_c(uint32 maxitem)
        {
          this->head = NULL;
          this->tail = NULL;
          this->curr = NULL;
          this->count = 0;
          this->maxitem = maxitem;
          this->nidx = 0;
        }

      ~linklist_c()
        {
          llnode_t *xcurr;
          llnode_t *xnext;

          if (this->count > 0)
            {
              xcurr = this->head;
              while(xcurr != NULL)
                {
                  xnext = this->xcurr->next;
                  delete this->xcurr->data;
                  free(xcurr);
                  xcurr = xnext;
                }
              this->head = NULL;
              this->tail = NULL;
              this->curr = NULL;
              this->count = 0;
              this->nidx = 0;
            }
        }
  };


#endif

现在我遇到的问题是在while循环中前两行的析构函数中引用了不完整类型。我已经添加了this关键字,似乎已经解决了这个问题。

我觉得令人费解的是为什么?

这是clang ++(v2011变体)产生的确切错误:

./linklist.h:71:18: error: member access into incomplete type 'llnode_t' (aka 'linklist_node_tag')
                  xnext = xcurr->next;
                               ^
./linklist.h:23:22: note: forward declaration of 'linklist_node_tag'
      typedef struct linklist_node_tag llnode_t;
                     ^
./linklist.h:72:17: error: member access into incomplete type 'llnode_t' (aka 'linklist_node_tag')
                  delete xcurr->data;

变量xnext和xcurr是在本地定义的,因此它们应该在堆栈上,并且它们应该直接指向结构。我错过了什么?

我在没有找到明确答案的情况下对此进行了相当多的研究。

Declaring a struct in a template class, undefined for member functions

Typedef inside template class doesn't work

Nested struct type in a template class

http://www.cplusplus.com/forum/beginner/94180/

0 个答案:

没有答案