转录一个大家也都可能遇到的问题...
如果你有遇到
: compile error 写说
: 从类型 「const BSTree<AdtTestObj>* const」 到类型 「BSTree<AdtTestObj>*」 的
?
: 换无效
: 初始化引数 2,属於 「BSTree<T>::iterator::iterator(BSTreeNode<T>*,
: BSTree<T>*) [with T = AdtTestObj]」
可能有小雷,不想看请按左键离开
===================================================
嗯, begin() and end() 不是 const 的确不太好...
要是我可能会龟毛的打死也不把 const 拿掉... XD
其实 iterator 里去存 _tree 也不是很有效率的写法 (我猜得没错的话, 每次
li++, li-- 都要 find 一下?)... 不过可能是比较好写的作法.
所以我想你的写法是 OK 啦, 要解决你的问题, 你可以试试:
iterator begin() const {
if(_root==0) return iterator(0, const_cast<BSTreeNode<T>*>(this));
BSTreeNode<T>* temp = findMin(_root);
return iterator(temp, const_cast<BSTreeNode<T>*>(this));
}
: 我的binary search tree已经写完了也测试成功
: 但是之前在写的过程中有遇到一个问题,我觉得我的解决方式不是很好
: 因此想请问老师:
: 我的 BSTree::iterator 内有两个 private data member:
: BSTreeNode<T>* _node;
: BSTree<T>* _tree;
: constructor 则是:
: iterator(BSTreeNode<T>* n= 0, BSTree<T>* p= 0): _node(n), _tree(p) {}
: iterator(const iterator& i) : _node(i._node), _tree(i._tree) {}
: 但是这样在 begin()、end()的地方会发生compile error:
: iterator begin() const { if(_root==0) return iterator(0, this);
: BSTreeNode<T>* temp = findMin(_root);
: return iterator(temp, this); }
: iterator end() const { return iterator(0, this); }
: compile error 写说
: 从类型 「const BSTree<AdtTestObj>* const」 到类型 「BSTree<AdtTestObj>*」 的转
: 换无效
: 初始化引数 2,属於 「BSTree<T>::iterator::iterator(BSTreeNode<T>*,
: BSTree<T>*) [with T = AdtTestObj]」
: 因此我把constructor改成
: iterator(BSTreeNode<T>* n= 0, const BSTree<T>* p= 0): _node(n), _tree(p) {}
: 且把data member改成 const BSTree<T>* _tree;
: 这样就不会有error
: 但是我在overload operator=的时候 需要把 传进去的iterator的_tree 一起copy
: 如此才能让
: BSTree::iterator li;
: li = bst.begin();
: 是合法的
: (虽然在老师的adtTest.h里面好像没有这种问题
: 因为 AdtType<AdtTestObj>::iterator li = _container.begin();
: 应该是呼叫copy constructor? )
: 因此 iterator 的 data member (BSTree<T>* _tree;) 不应该是const
: 但是不加const compile又不会过 (在costructor会有compile error)
: 後来我的解决方法是:
: 维持原本的写法
: 把 begin() 、 end()的 const 去掉 就OK了
: 但是以标准来说这两个应该要是const method吧
: 不知道有没有比较好的解决方法呢?
: 还是其实我的理解有不对的地方?
: 非常谢谢老师喔~
--
※ 编辑: ric2k1 来自: 61.224.42.19 (12/04 22:09)
1F:→ ysho:const BSTree<T>* _tree是说_tree指到的东西是const 12/04 22:41
2F:→ ysho:不代表_tree本身是const,所以overload operator=是没问题的 12/04 22:43
3F:→ ilway25:推楼上 12/04 23:27
4F:推 herbert570:我也在 const 上花了一些时间.... 12/05 01:27
5F:→ herbert570:请爱用 BSTree<T> const *, pointer to const BSTree 12/05 01:27
6F:推 a3785lexx:我怎麽都没想到要直接把整棵Tree给存起来! 12/05 04:33