【发布时间】:2018-12-27 03:52:50
【问题描述】:
我目前正在研究多态性及其与 C++ 中指针的关系。虽然我了解静态和动态分配与多态性之间的关系,但有一个案例让我感到困惑。
class Human
{
public:
virtual void talk();
};
void Human::talk(){ cout << "oink oink" << endl; }
class Doctor : public Human
{
public:
virtual void talk();
};
void Doctor::talk(){ cout << "ouaf ouaf" << endl; }
int main(int argc, char const *argv[])
{
Human h = Doctor();
Human* p = new Doctor();
delete p;
p = &h;
p->talk();
}
我不明白为什么p->speak() 输出oink oink 而不是ouaf ouaf。是因为 p 被重新分配到堆栈而不是堆上的位置吗?如果p可以重新分配,为什么不直接指向h的地址,决定在运行时调用Doctor中的talk()函数呢?
【问题讨论】:
标签: c++ pointers inheritance memory polymorphism