当存在这样的构造时:
Foo f;
f->bar(); //Here is called the class member access operator
但是,当“ f”是指向Foo类型的对象的指针时:
Foo* f = new Foo();
(*f)->bar(); //Here is also called the class member access operator
f->bar(); //<-- Which operator is called?
//Is it the pointer to member one (->*),
//or is the pointer-dereference one, or maybe both of them?
我还想问一下这种行为是否可以重载?
...
class Foo{
...
Foo* operator->() const{
cout << "overloaded" << endl;
return this;
}
};
Foo a;
Foo* b = new Foo();
a->bar(); //Here is called the overloaded ->
(*b)->(); //Again the overloaded one
b->bar(); //This calls something else
您不能->
在指针上重载运算符。当p
是指针时,p->bar()
将取消引用该指针并bar
在该对象上调用该函数。它不会调用任何重载的运算符。
另一方面,(*p)->bar()
将->
在指向类型上调用重载运算符。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句