[英]How to overload dereference operator?
How do I overload the dereference operator? 如何重载解除引用运算符? What would the declaration look like?
声明会是什么样? I'm creating a list class, but I am have trouble with the dereference operator.
我正在创建一个列表类,但是我对解引用运算符有麻烦。
Here is my function for overloading the dereference operator 这是我的函数重载解引用运算符
template <typename T>
T List_Iterator<T>::operator *(){
return current_link->value;
}
This is the data members in my iterator class 这是我的迭代器类中的数据成员
private:
/* Data Members */
Link<T>* current_link;
This is my link class 这是我的链接课
protected:
T value;
You should be returning a reference, not a copy: 您应该返回参考,而不是副本:
T& List_Iterator<T>::operator *() { .... }
Otherwise the semantics are confusing: you could not modify the object that you are "de-referencing". 否则,语义会造成混乱:您无法修改正在“取消引用”的对象。
You can also return by address. 您也可以按地址返回。 It's easier to write
a->b
than (*a).b
: 写
a->b
比(*a).b
更容易:
T* operator->() {
return ¤t_link->value;
}
You will certainly need a const-version of your iterator, that will basically do the same thing as the first one, with the const
versions of the "dereferencing" operators. 当然,您将需要迭代器的
const
版本,并且使用“解引用”运算符的const
版本,基本上可以完成与第一个迭代器相同的操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.