While overloading operator*
we do as follows:
T & operator * () { return *ptr; }
That means if I have:
SmartPtr<int> obj(new int());
*Obj = 20;
Cout << *obj;
Then the *obj
part is replaced by *ptr
so its as good as:
*Ptr=20
cout<<*ptr
Now while overloading operator->
we do the following:
T * operator -> () { return ptr; }
And it can be accessed as:
Obj->myfun();
What I don't understand here is after evaluating the obj->
is replaced by ptr
so it should look as follows:
ptrmyfun(); // and this is syntax error
Where am I going wrong?
C++ does not work like search/replace in a text editor. "obj1->" is not replaced by ptr verbatim, as if this was a line of text in a text file.
With:
Obj->myfun();
The fact that the ->
operator invokes a custom operator that returns ptr
:
T * operator -> () { return ptr; }
That doesn't mean that the original statement somehow becomes
ptrmyfun();
As if "Obj->" was replaced by "ptr". C++ simply does not work this way, like search/replace in a text editor.
The ->
operator results in the custom operator->()
getting invoked. That part, of how you understand operator overloading works, is correct.
But what happens is that, simply, the return value from the operator->
() becomes the actual pointer value to which the actual pointer dereference gets applied to.
So this becomes, essentially:
ptr->myfun();
That's all.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.