C++ 具有try-catch和异常抛出的方法
所以我有以下方法:C++ 具有try-catch和异常抛出的方法,c++,loops,types,try-catch,C++,Loops,Types,Try Catch,所以我有以下方法: template <class DT> //needs testing DT& LinkedSortedArrays<DT>::find (const DT& key) { list<SortedArray<DT>>::iterator it = SAList.begin(); for( ; it != SAList.end(); ++it){ try{ i
template <class DT> //needs testing
DT& LinkedSortedArrays<DT>::find (const DT& key)
{
list<SortedArray<DT>>::iterator it = SAList.begin();
for( ; it != SAList.end(); ++it){
try{
if (it == SAList.begin() && key < (*it)[0]) throw Exception();
return (*it).find(const_cast<DT&> (key));
} catch (ArrayException e) {
}
}
throw Exception();
}
模板//需要测试
DT&linkedSortedarray::find(常量DT&key)
{
list::iterator it=SAList.begin();
for(;it!=SAList.end();++it){
试一试{
if(it==SAList.begin()&&key<(*it)[0])抛出异常();
return(*it).find(const_cast(key));
}捕获(阵列异常e){
}
}
抛出异常();
}
我以前定义过类Exception
和arrayeexception
(*it).find(const_cast(key))
每次在当前搜索的特定数组类中未找到key
时,都会抛出一个ArrayExceptionSAList
是一个STL列表
。代码编译得很好。但是我还没有在我的程序中尝试过。为什么?我需要有人确认或纠正我所做的以下假设:
if(it==SAList.begin()&&key<(*it)[0])抛出异常()代码>抛出异常,这意味着它将抛出for循环之外,甚至方法之外,对吗
抛出异常()
将在方法外部引发异常++it
让我绞尽脑汁。帮忙无法将常量int转换为int&
(因为中的find()
(*it)。find(const_cast(key))
不是属于LinkedSortedArray
的那一个,而是另一个需要DT&variable和LinkedSortedArray
的find()
具有const DT&)类型的参数,我发现一个可能的解决方案可能是将其写成const_cast(key)
。我需要第二个意见catch
处理程序。如果没有找到这样的处理程序,程序将终止end
应该返回一个迭代器到结束处,而不是最后一个元素。除非那个容器的设计也很糟糕,但你必须查阅文档才能确定find
应该通过const
引用获取其参数。因为你不能,除非你想冒未定义行为的风险,否则你必须复制一份:
DT nonconstkey = key;
return it->find(nonconstkey);
为什么
find
不通过常量引用获取其参数?Profesor希望这样:/它基本上是属于另一个类的find
,数据结构由LinkedSortedArray
组成。您对ArrayException
和Exception
之间的关系做了哪些假设?是的,我知道,我非常清楚副本的需要。幸运的是,目前我只使用int
s。所以现在没有什么令人头痛的。@MooingDuck只是说Exception
不是ArrayException
的子类。我忘了提一下,ArrayException
是Exception
的子类。Yokhen没关系,它不会改变答案。