方法重写没有按预期工作

method overriding doesnt work as expected

抱歉,如果标题不是很好,我想不出别的了

我得到了这个程序:

class Animal
{
    private:
        int legs;
        string sound;
    protected:
        Animal(int l, string s) : legs(l), sound(s) {}
    public:
        Animal() {}
        string getClass()
        {
            return "Animal";
        }
        void printInfo()
        {
            cout <<"This is a(n) "<<getClass()<<". It has "<<getLegs()<<" legs and makes the sound: "<<getSound()<<"\n";
        }
        int getLegs()
        {
            return legs;
        }
        string getSound()
        {
            return sound;
        }
};

class Dog: public Animal
{
    public:
        Dog() : Animal(4,"bark")
        {
        }
        string getClass()
        {
            return "dog";
        }
};

int main()
{
    Animal a;
    Dog d;
    a.printInfo();
    d.printInfo();

    a=d;
    a.printInfo();
    return 0;
}

编译和 运行 结果如下:

This is a(n) Animal. It has 2002819627 legs and makes the sound:

This is a(n) Animal. It has 4 legs and makes the sound: bark

This is a(n) Animal. It has 4 legs and makes the sound: bark

为什么我在 d 上调用 printInfo() 时得到 "animal" 作为 class 而不是狗? (但仍然以某种方式让腿和声音正确)我的意思是,为什么 DoggetClassprintInfo() 上使用时不起作用;我做错了什么吗?

你得到当前腿数而不是动画名称的原因是因为构造函数是如何工作的, 当您创建 Dog class 时,您使用 "right" 腿数和

调用基础 class 构造函数

Dog() : Animal(4,"bark")

但是当你调用 printInfo 时 Dog 正在寻找这个函数但找不到它所以它会转到它的基数 class 并且在基数 class 处 class 是 "Animel". 您需要将基础 class getInfo ginather 更改为

virtual string getClass()
{
    return "Animal";
}

这会解决你的问题

有两点:

  1. 使用 virtual 方法,因此 getClass 对于 Animal() 实例将 return "Animal"getClass() 对于 Dog 实例将 return "dog".
  2. 您为 a 使用了默认构造函数,因此 legs 包含一些垃圾值,您需要对其进行初始化或删除默认构造函数。
class Animal
{
    private:
        int legs = DEFAULT_NUMBER_OF_LEGS;
//                 ^^^^^^^^^^^^^^^^^^^^^^
        string sound = "DEFAULT_SOUND";
//                     ^^^^^^^^^^^^^^^
    protected:
        Animal(int l, string s) : legs(l), sound(s) {}
    public:
        Animal() {}
        virtual string getClass()
//      ^^^^^^^
        {
            return "Animal";
        }
        void printInfo()
        {
            cout <<"This is a(n) "<<getClass()<<". It has "<<getLegs()<<" legs and makes the sound: "<<getSound()<<"\n";
        }
        int getLegs()
        {
            return legs;
        }
        string getSound()
        {
            return sound;
        }
};

class Dog: public Animal
{
    public:
        Dog() : Animal(4,"bark")
        {
        }
        string getClass() override
//                        ^^^^^^^^
        {
            return "dog";
        }
};

int main()
{
    Animal a;
    Dog d;
    a.printInfo();
    d.printInfo();

    a=d;
    a.printInfo();
    return 0;
}