![](/img/trans.png)
[英]why a conversion function declaration does not require at least one defining-type-specifier
[英]Why does my templated function require a conversion from one iterator to the other?
我正在嘗試實現一個二叉搜索樹容器。 目前我必須實現一個能夠返回迭代器或常量迭代器的 find() 函數。 我選擇重載 find 函數以適應這兩種可能性
MyIterator<treepair> find(const key& x)
{
return tree_search<MyIterator<treepair>>(root,x);
}
const_MyIterator<treepair> find(const key& x) const
{
return tree_search<const_MyIterator<treepair>>(root,x);
}
然后函數 tree_search 通過遍歷樹遞歸地找到包含所需鍵的節點:
template<typename iterator>
iterator tree_search(Node<treepair>* x, const key& y) const
{
if(x == nullptr)
{
std::cout<<"element not found"<<std::endl;
iterator x = end();//HERE I HAVE A PROBLEM
return x;
}
else if (y == x->value.first)
{
iterator i{x,tree_maximum()};
std::cout<<"element found"<<std::endl;
return i;
}
if(y < x->value.first)
return tree_search<iterator>(x->left,y);
else return tree_search<iterator>(x->right,y);
}
現在 end() 函數被重載以提供一個 const_iterator 和一個常規迭代器:
MyIterator<treepair> end(){
return MyIterator<treepair>{nullptr,tree_maximum()};
}
const_MyIterator<treepair> end() const{
return const_MyIterator<treepair>{nullptr,tree_maximum()};
}
但是我收到這個錯誤
test_on_iterators.cc:508:12: error: conversion from ‘const_MyIterator<std::pair<int, int> >’ to non-scalar type ‘MyIterator<std::pair<int, int> >’ requested
iterator x = end();
這個錯誤是由於類型之間的轉換需要嗎? 編譯器不應該根據它必須生成的迭代器類型來選擇想要的 end() 函數嗎?
編譯器不應該根據它必須生成的迭代器類型來選擇想要的 end() 函數嗎?
不。
tree_search()
是一個const
方法。 這意味着它的this
指針指向一個const
對象(即使調用對象tree_search()
並不是真正的const
)。
因此,當tree_search()
內部調用end()
,它會調用可在const
對象上調用的重載。 該重載返回一個const_MyIterator
。 然后tree_search()
嘗試將該const_MyIterator
分配給非常量MyIterator
,這是您收到錯誤的地方,因為沒有定義從const_MyIterator
到MyIterator
轉換。
您需要使x
成為const_MyIterator
以匹配end()
的const
版本返回的內容。
您還應該讓tree_search()
返回一個const_MyIterator
,而不是返回一個非常量iterator
。 如果您希望tree_search()
返回非常量Iterator
,則不要將tree_search()
聲明為const
方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.