template <typename T> typename btree<T>::iterator btree<T>::find(const T& elem) { //Implementation }
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
解决方法
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 举报,一经查实,本站将立刻删除。