[英]No appropriate default constructor available with template implementation in Cpp
我正在嘗試在 C++ 中手動實現 Stack。 我想將此實現用於許多數據類型,因此我嘗試通過在 C++ 中使用模板來實現它。 然后我的堆棧 class 的構造函數出現錯誤。 這是我的代碼
#include<iostream>
#include<string>
using namespace std;
template <class T>
class Node
{
public:
T data;
Node* next;
Node(T value)
{
data = value;
next = NULL;
}
};
template <class T>
class Stack :public Node<T>
{
public:
Node<T>* head;
Stack()
{
head = NULL;
}
~Stack()
{
Node<T>* current = head;
Node<T>* next;
while (current != NULL) {
next = current->next;
delete current;
current = next;
}
head = NULL;
}
T top()
{
return head->data;
}
void push(Node<T>* newNode)
{
newNode->next = head;
head = newNode;
}
void pop()
{
Node<T>* temp = head;
head = head->next;
delete temp;
}
bool isEmpty()
{
return head == NULL;
}
};
錯誤是:“節點”:沒有合適的默認構造函數可用
你們能解釋一下發生了什么並給我一些建議嗎!!!
堆棧 class 不應該繼承節點 class,它應該組成它,您應該從堆棧 ZA2F2ED4F8EBC2CBBDZ4C2 中刪除 inheritance 關系,它應該看起來像這樣:
template <class T>
class Stack
當創建派生自基礎 class 的 object 時,還會創建基礎 class 子對象。 這個:
Stack()
{
head = NULL;
}
和寫法一樣:
Stack() : Node<T> () {
head = NULL;
}
也就是說:當您沒有顯式調用基本 class 構造函數時,將調用其默認構造函數。 您的Node
沒有默認構造函數(默認構造函數是可以不帶參數調用的構造函數)。
實際上,看起來Stack
一開始就不應該從Node
繼承。
作為旁注,您應該在構造函數主體中初始化成員而不是賦值。 初始化它們的一種方法是成員初始化列表。 並且更好地使用nullptr
而不是NULL
:
Stack() : Node<T>(), head(nullptr)
{}
PS如果不涉及模板,你會得到同樣的錯誤。 我建議為一種特定類型編寫相同的代碼,然后將其轉換為模板。 這樣,您一次可以做一件事。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.