在这种情况下,哪个操作员被调用

Which operator is called in that case

本文关键字:操作员 调用 这种情况下      更新时间:2023-10-16

有这样的结构时:

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()将在指向类型上调用Overloaded ->操作员。