【问题标题】: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()函数呢?

【问题讨论】:

    标签: c++ pointers inheritance memory polymorphism


    【解决方案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 向他解释为什么他的期望是不合理的。
    猜你喜欢
    • 2020-07-16
    • 1970-01-01
    • 2013-01-07
    • 2015-03-09
    • 1970-01-01
    • 1970-01-01
    • 2015-07-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多