I have defined a struct within the protected section of a parent class, which I would like to use in an inherited class.
This works as expected if the parent/child classes aren't templated classes. But does not compile as-is below.
Specifically, the compiler (clang 8.0.1) reports:
inheritance_example.cpp:33:26: error: unknown type name 'Node'
this->head = new Node(toAdd);
From what I have read, I am guessing that the template type specification isn't being assigned to Node
, and is thus not being found by the inherited class, but trying the fixes I have found in that vein (i.e. add something along the lines of using Parent<T>::Node
, or add a type specifier to the call to the Node constructor), have not worked for me.
Any ideas on how to fix this issue?
#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;
}
Aucun commentaire:
Enregistrer un commentaire