协变返回类型和调度

时间:2014-06-16 07:43:03

标签: c++ covariance virtual-functions

我对这个简单的程序感到困惑:

#include <iostream>

using namespace std;

struct Base {
  virtual ~Base() {}
  virtual Base* concrete() { cout << "concrete returning base - "; return this;}
  void stat() { cout << "I'm a BASE\n";}
};

struct Derived: Base {
  Derived* concrete() override { cout << "concrete returning derived - "; return this;}
  void stat() { cout << "I'm a DERIVED\n";}
};


int main() {
  Base * bd = new Derived;
  bd->stat();  // prints: "I'm a BASE"
  bd->concrete()->stat(); //prints: "concrete returning derived - I'm a BASE"

  delete bd;
  return 0;
}

为什么最后一行打印concrete returning derived - I'm a DERIVED?这里发生了什么?

1 个答案:

答案 0 :(得分:4)

你误解了协变返回类型的效用......当调用上下文知道它正在处理Derived类型的对象时,它就会启动:

Derived d;
d->concrete()->stat();

在您的情况下,在concrete上调用Base*,因此虽然它以多态方式发送并返回Derived*,但该指针在调用上下文中被视为Base*Base*静态类型决定了对stat()的静态调度。