简体   繁体   English

C ++重载 - >运算符,它是如何工作的?

[英]C++ Overloading -> operator, how does it work?

I was trying to implement a smart pointer class similar to the standard library auto_ptr and accordingly I had to overload the -> operator for the same. 我试图实现类似于标准库auto_ptr的智能指针类,因此我不得不重载 - >运算符。 Here is my code 这是我的代码

template <typename T>
class SmartPtr
{

   T * operator -> ()
  {
    return _pAct;
  }

 private:
 T * _pAct;
};

Rest of the implementation is not shown so as to avoid diversion from my query. 其余的实现未显示,以避免从我的查询转移。

Now I create a SmartPtr of class A and call a method Show() present in A on it : 现在我创建一个A类的SmartPtr并调用A中的方法Show():

SmartPtr smPtr(new A);
smPtr->Show();

Here is my query(don't know if its valid also) 这是我的查询(不知道它是否也有效)

Since SmartPtr::operator->() return A*, the call to show should translate to (A*)Show. 由于SmartPtr :: operator - >()返回A *,因此对show的调用应转换为(A *)Show。 Why it translates to (A*)->Show() ? 为什么它转换为(A *) - > Show()?

or in other words how does smPtr->Show() mean call Show() on whatever smPtr->() operator returns ? 或者换句话说,smPtr-> Show()是如何在smPtr - >()运算符返回时调用Show()?

Because operator -> applies sequentially until it can't be applied any more. 因为operator ->按顺序应用,直到无法再应用为止。

13.5.6 Class member access [over.ref] 13.5.6类成员访问[over.ref]

1) operator-> shall be a non-static member function taking no parameters. 1) operator->应该是一个不带参数的非静态成员函数。 It implements class member access using -> postfix-expression -> id-expression An expression x->m is interpreted as (x.operator->())->m for a class object x of type T if T::operator->() exists and if the operator is selected as the best match function by the overload resolution mechanism (13.3). 它使用-> postfix-expression -> id-expression实现类成员访问如果T::operator->()表达式x->m被解释为(x.operator->())->m表示类型为T的类对象x T::operator->()存在,如果操作符被重载决策机制选为最佳匹配函数(13.3)。 (emphasis mine) (强调我的)

Which means, in your case, it translates to: 这意味着,在您的情况下,它转换为:

smPtr.operator->()->Show();
          |           |
      returns A*   call Show on the A*

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

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