简体   繁体   English

重载“->”成员访问运算符

[英]Overloading '->' member access operator

While overloading operator* we do as follows: 在重载operator*我们执行以下操作:

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: 然后,将*obj部分替换为*ptr ,使其与以下各项一样好:

*Ptr=20
cout<<*ptr

Now while overloading operator-> we do the following: 现在,在重载operator->同时,我们执行以下操作:

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: 我在这里不了解的是在评估obj->之后将其替换为ptr因此它应如下所示:

ptrmyfun(); // and this is syntax error

Where am I going wrong? 我要去哪里错了?

C++ does not work like search/replace in a text editor. C ++不能像在文本编辑器中搜索/替换一样工作。 "obj1->" is not replaced by ptr verbatim, as if this was a line of text in a text file. “ obj1->”不会被逐字记录所代替,就像这是文本文件中的一行文本一样。

With: 附:

Obj->myfun();

The fact that the -> operator invokes a custom operator that returns ptr : ->运算符调用返回ptr的自定义运算符的事实:

T * operator -> () { return ptr; }

That doesn't mean that the original statement somehow becomes 这并不意味着原始的声明会以某种方式变为

ptrmyfun();

As if "Obj->" was replaced by "ptr". 好像“ Obj->”被“ ptr”代替。 C++ simply does not work this way, like search/replace in a text editor. C ++根本无法以这种方式工作,就像在文本编辑器中进行搜索/替换一样。

The -> operator results in the custom operator->() getting invoked. ->运算符导致调用自定义operator->() 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. 但是发生的是,简单地,来自operator-> ()的返回值变成了实际指针取消引用所应用于的实际指针值。

So this becomes, essentially: 因此,这基本上变成了:

ptr->myfun();

That's all. 就这样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM