0
因此,當我的鏈接列表類只使用ints而不是模板T時,它完美地工作,但是當我經歷並將所有事情都改變爲模板化時,它給我和錯誤說「使用模板類LinkedList需要模板參數「。C++使用模板類LinkedList需要模板參數
#ifndef LINKEDLIST_H
#define LINKEDLIST_H
#include <iostream>
#include <memory>
template<typename T>
class LinkedList
{
private:
struct Node
{
T data;
std::shared_ptr<Node> next;
Node(T d, std::shared_ptr<Node> n)
:data(d)
,next(n)
{}
Node()
{};
T getData()
{
return data;
}
};
std::shared_ptr<Node> head;
std::shared_ptr<Node> current;
public:
LinkedList()
:head()
{}
LinkedList(LinkedList& other)
:head(Clone(other.head))
{}
^This is where I think the problem is but did I just forget to replace an int somewhere? I've looked this over a lot and I haven't found anything but I could just be blind.
std::shared_ptr<Node> getStart() const
{
return head;
}
//Insertion
void InsertAt(T value, std::shared_ptr<Node> &n)
{
n = std::make_shared<Node>(value, n);
}
void Insertion(T value)
{
Insertion(value, head);
}
void Insertion(T value, std::shared_ptr<Node> &n)
{
if (!n)
{
InsertAt(value, n);
return;
}
if (value > n->data)
Insertion(value, n->next);
else
InsertAt(value, n);
}
//Deletion
void Remove(T value)
{
Remove(value, head);
}
void Remove(T value, std::shared_ptr<Node>& n)
{
if (!n) return;
if (n->data == value)
{
n = n->next;
Remove(value, n);
}
else
{
Remove(value, n->next);
}
}
void for_each(const std::shared_ptr<Node> &n)
{
if(!n) return;
else
{
std::cout<<n->data<<std::endl;
for_each(n->next);
}
}
std::shared_ptr<Node> Clone(std::shared_ptr<Node> n) const
{
if(!n) return nullptr;
return std::make_shared<Node>(n->data, Clone(n->next));
}
LinkedList& operator = (const LinkedList &list)
{
head = list.head;
this->Clone(head);
return *this;
}
};
#endif
我編寫的代碼,而無需使用'G ++ -c -std = C++ 11 q.cpp'錯誤(G ++版本4.8.1) –
能告訴你你使用這個類模板的代碼部分(因爲我認爲那是你的錯誤發生的地方,你是否明確指定了實例化的類型?) –
這個錯誤意味着你沒有指定模板參數,而實例化模板。在上面的代碼中沒有模板實例化。 –