【发布时间】:2012-10-23 22:01:25
【问题描述】:
所以我有以下方法:
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();
}
我之前已经定义了 Exception 和 ArrayException 类。 (*it).find(const_cast<DT&> (key)) 每次在当前正在搜索的特定 Array 类中找不到 key 时都会抛出 ArrayException。 SAList 是 STL List。代码编译得很好。但是我还没有在我的程序中尝试过。为什么?我需要有人确认或纠正我所做的以下假设:
- 每当
if (it == SAList.begin() && key < (*it)[0]) throw Exception();抛出异常,就意味着它会抛出for循环之外,甚至是方法之外,对吧? - 我几乎可以肯定最后一行
throw Exception();会在方法外抛出异常。 - for循环的排列方式,不会跳过SAList的第一个元素吧?我的意思是,我在整个互联网上都看到了这个特定的代码,它用于迭代列表的所有元素,就好像它是标准的或完美的一样,但是......
++it正在扭曲我的大脑。帮忙? - 我收到
can't convert const int to int&的错误(因为(*it).find(const_cast<DT&> (key))中的find()不是属于LinkedSortedArrays的那个,而是另一个需要DT& 变量和LinkedSortedArrays的find()具有 const DT&) 类型的参数,我发现一个可能的解决方案可能是将其写为const_cast<DT&> (key)。我需要对此提出第二意见。
最后,我了解这是否不是一个具体问题,因此我会被否决和/或问题被关闭。我真的不知道还能去哪里问。 如果是我在错误的地方问的情况。我很抱歉。
【问题讨论】:
-
为什么
find不通过 const 引用获取其参数? -
教授希望这样:/ 它基本上是属于另一个类的
find,它与LinkedSortedArrays一起构成了数据结构。