【发布时间】:2016-02-16 12:59:14
【问题描述】:
所以我有一个非常简单的单链表实现示例。我有一个begin 函数作为forward_list 的公共成员,它返回指向列表的第一个(根)元素的指针。
现在,由于它返回一个指向包含各种成员的 _node 对象的指针,据我了解,必须提供取消引用运算符重载,以便 _node 知道在取消引用时返回什么。
在取消引用运算符定义中,我尝试返回_node 的value,这一切似乎都很合乎逻辑,因为begin 返回一个_node,这意味着取消引用begin 会给我value在_node 后面。显然不是,正如 MSVC 编译器告诉我的那样:binary '<<': no operator found which takes a right-hand operand of type '_node<TType>' (or there is no acceptable conversion)
#include <iostream>
#include <cstddef>
//forward declarations
template<class TType> class forward_list;
template<class TType>
class _node
{
private:
TType key;
_node *next;
friend class forward_list<TType>;
public:
TType operator*() { return this->key; } //problem is here
};
template<class TType>
class forward_list
{
private:
_node<TType> *_root;
_node<TType> *_tail;
std::size_t _size;
private:
void _add_node_front(const TType &new_key)
{
_node<TType> *new_node = new _node<TType>{ new_key, this->_root };
if (this->_root == nullptr)
this->_tail = new_node;
this->_root = new_node;
++this->_size;
}
public:
forward_list() : _root(nullptr), _tail(nullptr), _size(0) {}
void push_front(const TType &new_key) { this->_add_node_front(new_key); }
_node<TType> *begin() { return this->_root; }
};
int main()
{
forward_list<int> l;
l.push_front(23);
l.push_front(57);
l.push_front(26); //26 57 23
std::cout << *l.begin(); //expected to print out "26"
}
编辑:: 感谢 Joachim Pileborg 的建议。具有以下更改的魅力:
_node<TType> begin() { return *this->_root; }
【问题讨论】:
标签: c++ c++11 operator-overloading