指针重新分配和多态

Posted

技术标签:

【中文标题】指针重新分配和多态【英文标题】:Pointer Reallocation and Polymorphism [duplicate] 【发布时间】: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-&gt;speak() 输出oink oink 而不是ouaf ouaf。是因为 p 被重新分配到堆栈而不是堆上的位置吗?如果p可以重新分配,为什么不直接指向h的地址,决定在运行时调用Doctor中的talk()函数呢?

【问题讨论】:

【参考方案1】:

第一行 Human h = Doctor();首先创建 h 然后创建 Doctor 对象,然后调用 human 的复制构造函数。 H 被声明为人类,因此在复制构造后它将保持人类。

#include <iostream>

using namespace std;

class Human

    public:
        virtual void talk();
        Human()
        
            cout<<"Human"<<endl;
        
        Human(const Human & h)
        
            cout<<"Copy Human"<<endl;
        
;

void Human::talk() cout << "oink oink" << endl; 

class Doctor : public Human

    public:
        virtual void talk();
        Doctor()
        
            cout<<"Doctor"<<endl;
        
        Doctor(const Human & h)
        
            cout<<"Copy Doctor"<<endl;
        
;

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();


【讨论】:

如果您使用int j; j=0.5;,您是否希望j 具有除int 以外的任何类型? 不,我不希望 j 有除 int 以外的任何类型。先生,我不相信您的观点,所以我编辑了我的答案。 我的评论更多是针对 OP 向他解释为什么他的期望是不合理的。

以上是关于指针重新分配和多态的主要内容,如果未能解决你的问题,请参考以下文章

如果堆分配的对象被销毁并重新分配指针,Qt 的信号和插槽系统会工作吗?

当指针指向的对象被另一个类的实例删除时重新分配指针

使用结构更新指针进行重新分配时出现问题[重复]

当向量需要更多内存并重新分配内存时,指针会发生啥?

重新分配初始化指针的原因是啥?

重新分配给包含自动释放对象的指针是不是不正确?