首页 > 解决方案 > 方法覆盖没有按预期工作

问题描述

对不起,如果标题不是很好,我想不出别的了

我得到了这个程序:

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;
}

编译和运行结果如下:

这是一个(n)动物。它有 2002819627 条腿并发出声音:

这是一个(n)动物。它有 4 条腿并发出声音:吠声

这是一个(n)动物。它有 4 条腿并发出声音:吠声

为什么当我打电话时我得到“动物”作为班级而不是printInfo()d?(但仍然以某种方式使腿和声音正确)我Dog的意思是,为什么getClass在使用时不起作用printInfo();难道我做错了什么?

标签: c++inheritanceoverriding

解决方案


有两点:

  1. 使用virtual方法,getClass例如Animal()会返回"Animal"getClass()例如Dog会返回"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;
}

推荐阅读