微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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) { /* .... */ }
};

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

原文地址:https://www.jb51.cc/c/119796.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐