在这种情况下调用哪个运算符

时间:2014-01-19 18:39:26

标签: c++

当有这样的结构时:

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

1 个答案:

答案 0 :(得分:3)

您不能在指针上重载->运算符。当p是指针时,p->bar()将取消引用指针并调用对象上的bar函数。它不会调用任何重载的运算符。

另一方面,(*p)->bar()将调用指向类型的重载->运算符。