替代方法无法正常工作

问题描述 投票:-1回答:1

对不起,如果标题不是很好,我想不出其他任何东西

我有这个程序:

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

在此编译并运行结果:

这是一种动物。它具有2002819627的腿并发出声音:

这是一种动物。它有4条腿,发出声音:[吠声

这是一种动物。它有4条腿,发出声音:[吠声

为什么当我在printInfo()上调用d时,我得到“动物”作为类而不是狗? (但仍然可以使腿和声音以某种方式正确纠正)我的意思是,为什么DoggetClassprintInfo()上使用时不起作用;我在做错什么吗?

c++ inheritance overriding
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.