初始化在模板化父类中定义的结构

马修·罗素

我已经在父类的protected部分内定义了一个结构,我想在继承的类中使用该结构。

如果父/子类不是模板类,则可以按预期工作。但是下面没有按原样编译。

具体来说,编译器(clang 8.0.1)报告:

inheritance_example.cpp:33:26: error: unknown type name 'Node'
        this->head = new Node(toAdd);

从我的阅读中,我猜测模板类型规范未分配给Node,因此继承的类未找到该模板类型规范,而是尝试按照此方法找到的修复方法(即,沿着using Parent<T>::Node,或将类型说明符添加到对Node构造函数的调用中),对我没有用。

关于如何解决此问题的任何想法?

#include<iostream>

template <class T>
class Parent 
{
protected:
   struct Node
   {
      Node(int value) 
      {
         this->data = value;
         this->next = nullptr;
      };

      ~Node() {};
      Node* next;
      int data;
   };

   Node* head;

public:
   Parent() {};
   ~Parent() {};
};

template <class T>
class Child : Parent<T>
{
public:

   Child() 
   {
      this->head = nullptr;
   };

   ~Child()
   {
      delete this->head;
      this->head = nullptr;
   };

   void dummyAdd(T toAdd) {
      this->head = new Node(toAdd);
   };

   void dummyPrint() 
   {
      std::cout << this->head->data << std::endl;
   };
};

int main() 
{
   Child<int> t;
   t.dummyAdd(5);
   t.dummyPrint();
   return 0;
}
杰乔

为了将评论打包成答案!

Node是一个从属名称,因此您需要在此处使用关键字typenamedummyAdd功能中的含义,您需要

void dummyAdd(T toAdd) 
{
   this->head = new typename Parent<T>::Node(toAdd);
   //               ^^^^^^^^^^^^^^^^^^^^ 
};

但是,这有点冗长/输入更多。因此在中提供类型别名将是一个好主意。NodeChild

template <class T>
class Child : Parent<T> 
{
   using Node = typename Parent<T>::Node;  // template type alias

public:
   void dummyAdd(T toAdd) 
   {
      this->head = new Node(toAdd);       // now you can this
   };

   // other code...
};

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章