【发布时间】:2020-06-30 17:47:05
【问题描述】:
我在父类的受保护部分中定义了一个结构,我想在继承的类中使用它。
如果父/子类不是模板类,这将按预期工作。但不会按如下方式编译。
具体来说,编译器(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;
}
【问题讨论】:
-
this->head = new typename Parent<T>::Node(toAdd);? -
成功!谢谢你:)
-
@ioums 您应该将其添加为答案。
-
类似 question 有同样的问题 - 需要使用
typename关键字。
标签: c++ class c++11 templates class-template