How to overload the indirection operator? (C++)

霸气de小男生 提交于 2019-12-01 03:37:47

You overloaded the multiply operator. Take the parameter out to make it an indirection operator.

template<class T>
T list<T>::iterator::operator*()
{
    return ((this->lstptr)->current)->data;
}

You should also have it return a reference if you want code like *IT = 3; to compile.

template<class T>
T& list<T>::iterator::operator*()
{
    return ((this->lstptr)->current)->data;
}

You have two problems here; the first is that you have accidentally overloaded the multiplication operator and not the dereferencing operator; the second is that you haven't returned a reference type.

The first issue comes about as a result of the number of parameters. Every non-static member function of a class has an additional "hidden" parameter: this. this is, of course, the pointer to the object the function is being invoked on. As a result, you have actually declared a version of the operator taking two parameters. By removing the second iterator parameter and operating on this, you will be overloading the unary * and not the binary one.

The second issue is a minor one of return type; you are returning a copy to the original object and not the original object itself. Declare the return type as T& to return a reference.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!