如何将方法从父级重载到子级

时间:2014-07-25 07:31:24

标签: c++ oop

我的动物类

class Animal
{
protected:
    string animalName, sounds, colors, wayOfDrinking, wayOfEating;
    int numberOfLegs;
    bool hasTail;

public:
    Animal() {} //default constructor
    ~Animal() {} //destructor

    void SetAnimal(string, string, string, string, string, int, bool);
    Animal GetAnimal(void);
};

class WildAnimal : public Animal
{
    string animalPrey, attackStyle;

public:
    void SetAnimal(string, string);
};

class TameAnimal : public Animal
{
    string predator, hidingStyle;
};

我在main中的实例:

WildAnimal lion;
    lion.SetAnimal("Lion", "Roar!", "Gold", "Stick the tongue out", "Tear the flesh", 4, true);
    lion.SetAnimal("Stag", "Pounce");

我在“Gold”部分收到错误,说我给的参数太多了。如何成功地将SetAnimal方法从类动物重载到野生动物?谢谢!

1 个答案:

答案 0 :(得分:2)

在派生类中声明成员函数时,它会隐藏同名的所有基类成员函数。要将基类成员函数放入派生类的作用域中,以便通过名称查找找到它,添加using

class WildAnimal : public Animal
{
    string animalPrey, attackStyle;

public:
    void SetAnimal(string, string);
    using Animal::SetAnimal;
};

Demo