I have a question about the following sample program about overloading -> operator, same across in a C++ tutorial:
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. I understand that "ob" is not a pointer, but since "class myclass" has defined the operator "->", "ob->i" is valid (syntactically), so far good. However, "ob->" returns a pointer, and I don't see how it is de-referenced to get access to member "i" and setting it.
I am assuming the above explanation will also explain how in line 19 "ob->i" is printed as an 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.
I hope it gets clearer from that.
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.