简体   繁体   English

重载operator - >访问数据成员

[英]overloading operator -> to access data member

I have a question about the following sample program about overloading -> operator, same across in a C++ tutorial: 我有一个关于以下关于重载的示例程序的问题 - >运算符,在C ++教程中是相同的:

 5     class myclass
 6     {
 7         public:
 8         int i;
 9
10         myclass *operator->()
11         {return this;}
12     };
13
14     int main()
15     {
16         myclass ob;
17
18         ob->i = 10;
19         cout << ob.i << " " << ob->i << endl;
20
21         return 0;
22     }

$ ./a.out
10 10

I am trying to understand how line 18 works. 我试图了解第18行是如何工作的。 I understand that "ob" is not a pointer, but since "class myclass" has defined the operator "->", "ob->i" is valid (syntactically), so far good. 我理解“ob”不是一个指针,但由于“class myclass”定义了运算符“ - >”,“ob-> i”是有效的(语法),到目前为止还不错。 However, "ob->" returns a pointer, and I don't see how it is de-referenced to get access to member "i" and setting it. 但是,“ob->”返回一个指针,我看不到如何取消引用它来访问成员“i”并进行设置。

I am assuming the above explanation will also explain how in line 19 "ob->i" is printed as an int. 我假设上面的解释也将解释第19行“ob-> i”是如何打印为int的。

Thank you, Ahmed. 艾哈迈德,谢谢你。

operator->在一个链中被调用,直到它不再被调用 - 在你的情况下,它实际上被调用了两次 - 一次,你的对象上的重载操作符,它返回一个指针,第二次,内置的操作符,取消引用指针并访问该成员。

x->y is equivalent to x.operator->()->y if x is a class object and an overloaded member operator-> is found. x->y等效于x.operator->()->y如果x是一个类对象并且找到了重载的成员operator->

I hope it gets clearer from that. 我希望它能从中得到更清楚。

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

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