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

后端 未结 2 1493
既然无缘
既然无缘 2021-01-12 01:30

I\'m trying to create an iterator class as a member-class for a list class, and am trying to overload the indirection operator (*) to access the list it\'s pointing to:

2条回答
  •  忘掉有多难
    2021-01-12 01:51

    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.

提交回复
热议问题