重载虚拟运算符 - >()

iam*_*ind 9 c++ virtual overriding operator-overloading

这只是一个实验代码.

struct B
{
  virtual B* operator -> () { return this; }
  void foo () {} // edit: intentionally NOT virtual
};

struct D : B
{
  virtual D* operator -> () { return this; }
  void foo () {}
};

int main ()
{
  B &pB = *new D;
  pB->foo();  // calls B::foo() !
}
Run Code Online (Sandbox Code Playgroud)

我知道operator必须使用对象或引用来调用它; 因此在上述情况下确实参考pB仍然坚决的对象B?虽然这是不实际的,但出于好奇,有没有什么办法来调用D::operator ->通过pB

Nem*_*emo 8

我认为它是在调用D::operator->,但返回值被视为a B*,因此B::foo()被调用.

这是协变返回类型行为的工件.