我被这个简单的程序弄糊涂了:
#include <iostream>
using namespace std;
struct Base {
virtual ~Base() {}
virtual Base* concrete() { cout << "concrete returning base - "; return this;}
void stat() { cout << "I'm a BASEn";}
};
struct Derived: Base {
Derived* concrete() override { cout << "concrete returning derived - "; return this;}
void stat() { cout << "I'm a DERIVEDn";}
};
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
?这是怎么回事?
你误解了协变返回类型的效用…当调用上下文知道它正在处理一个Derived
类型的对象时,它就会启动:
Derived d;
d->concrete()->stat();
在您的情况下,concrete
在Base*
上被调用,因此尽管它是多态调度并返回Derived*
,但该指针在调用上下文中被视为Base*
,并且它是Base*
静态类型,确定静态调度到stat()
。