c – 如何使用两个函数,一个返回迭代器,另一个返回const_iterator

所以我有一个名为find的函数,它有两个版本:
template <typename T> 
typename btree<T>::iterator btree<T>::find(const T& elem)
{
    //Implementation
}

一个是const_iterator版本:

template <typename T> 
typename btree<T>::const_iterator btree<T>::find(const T& elem) const
{
    //Implementation
}

在我的测试文件

btree<char>::iterator it = myTree.find('M');

一切正常,但是当我使用const_iterator版本时:

btree<char>::const_iterator it = myTree.find('M');

它给了我错误

error: conversion from ‘btree_iterator’ to non-scalar type ‘const_btree_iterator’ requested

这显然意味着find只使用迭代器(非const)版本.我知道C应该自动调用const_iterator版本 – 如果我做的一切正确的话.所以问题是,我可能做错了什么?

迭代器类是:

class btree_iterator和类const_btree_iterator,它只是btree_iterator的复制粘贴,名称已更改

以下是完整的源代码
btree_iterator.h(包括const_btree_iterator)http://pastebin.com/zQnj9DxA
btree.h http://pastebin.com/9U5AXmtV
btree.tem http://pastebin.com/U9uV3uXj

解决方法

所有标准容器都实现了非const到const迭代器的转换(如 specified in the requirements for the Container concept):

The type of iterator used to iterate through a container’s elements. The iterator’s value type is expected to be the container’s value type. A conversion from the iterator type to the const iterator type must exist.

你需要像这样的转换构造函数

class btree_iterator;
class const_btree_iterator
{
       // ....
       public:
              const_btree_iterator(const btree_iterator& rhs) { /* .... */ }
//optionally: const_btree_iterator& operator=(const btree_iterator& rhs) { /* .... */ }
};

我也投入了赋值运算符,但我认为它是多余的

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...