상속 된 클래스에서 사용하고 싶은 부모 클래스의 보호 섹션 내에 구조체를 정의했습니다.
부모 / 자식 클래스가 템플릿 클래스가 아닌 경우 예상대로 작동합니다. 그러나 아래에서 그대로 컴파일하지 않습니다.
특히 컴파일러 (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
종속 된 이름이므로 거기에 키워드typename
를 사용해야 합니다 . dummyAdd
기능 에서 의미하는 것은
void dummyAdd(T toAdd)
{
this->head = new typename Parent<T>::Node(toAdd);
// ^^^^^^^^^^^^^^^^^^^^
};
그러나 그것은 약간 장황하고 더 많은 타이핑입니다. 따라서 제공하는 유형 별칭을 위해 Node
(가)에서 Child
좋은 아이디어가 될 것입니다.
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] 삭제
몇 마디 만하겠습니다