[英]constructor template call 'no matching function to call'
我目前正在為項目編寫樹數據結構,如下所示:
template<typename T>
class tree
{
public:
tree(T const&);
// ...
private:
// ...
std::auto_ptr<node<T>> mRoot;
};
template<typename T>
tree<T>::tree(T const& data):
mDepth(0),
mRoot(nullptr)
{
mRoot = new node<T>(data, nullptr, nullptr, nullptr, nullptr, nullptr);
}
構造函數應使用數據作為輸入來初始化樹以創建根節點。
節點構造函數如下所示:
template<typename T>
struct node
{
// constructor & destructor
node(T const&,
std::auto_ptr<node<T>>,
std::auto_ptr<node<T>>,
std::auto_ptr<node<T>>,
std::auto_ptr<node<T>>,
std::auto_ptr<node<T>>);
// member
T data;
std::auto_ptr<node<T>> parent;
std::auto_ptr<node<T>> firstChild, lastChild;
std::auto_ptr<node<T>> nextSibling, prevSibling;
int numChildren;
};
template<typename T>
node<T>::node(T const& data,
std::auto_ptr<node<T>> parent,
std::auto_ptr<node<T>> firstChild,
std::auto_ptr<node<T>> lastChild,
std::auto_ptr<node<T>> nextSibling,
std::auto_ptr<node<T>> prevSibling):
data(data),
parent(nullptr),
firstChild(nullptr),
lastChild(nullptr),
nextSibling(nullptr),
prevSibling(nullptr),
numChildren(nullptr)
{}
但是如果我嘗試在我的主要函數中這樣調用它
int foo = 1;
tree<int> mytree = tree<int>(foo);
失敗並顯示以下錯誤:
tree.h: In instantiation of 'tree<T>::tree(const T&) [with T = int]':
main.cpp:9:35: required from here
tree.h:39:9: error: no matching function for call to 'node<int>::node(const int&, std::nullptr_t, std::nullptr_t, std::nullptr_t, std::nullptr_t, std::nullptr_t)'
mRoot = new node<T>(data, nullptr, nullptr, nullptr, nullptr, nullptr);
主要問題是,我有點重用了舊的自我實現的鏈表中的結構,其中一切正常。
也許我只是盲目地找到主要的錯誤,但是如果你們中的一個對此有想法的話,那就太好了。
std::auto_ptr
沒有從指針類型進行隱式轉換,這意味着不允許這種初始化:
std::auto_ptr<node<T>> n = nullptr;
您可以通過將相關的構造函數簽名更改為來解決緊迫的問題
node(T const&, node*, node*, node*, node*, node*);
請注意,您的構造函數實現甚至沒有嘗試使用auto_ptr
參數。 如果進行了適當的配置,編譯器應向您發出警告。 大概您想做這樣的事情:
template<typename T>
node<T>::node(T const& data,
node<T>* parent,
node<T>* firstChild,
node<T>* lastChild,
node<T>* nextSibling,
node<T>* prevSibling):
data(data),
parent(parent),
firstChild(firstChild),
lastChild(lastChild),
nextSibling(nextSibling),
prevSibling(prevSibling),
numChildren(numChildren)
{}
最后,請注意,C ++ 11中不推薦使用std::auto_ptr
。 如果可以使用比C ++ 03更新的方言,請考慮使用std::unique_ptr
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.