有没有办法专门化继承对象的一般方法

时间:2016-12-23 16:34:57

标签: c++ inheritance polymorphism

我有两个专门的对象:

class Food {};
class Fruit : public Food {};
class Vegetable : public Food {};

然后我有一个将继承的父类:

class Parent
{
    virtual void say(Food* obj) { std::cout << "The object is food" << std::endl; }
};

来自父母的继承类。

class Child : public Parent
{
    virtual void say(Fruit* obj) { std::cout << "The object is a fruit" << std::endl; }
    virtual void say(Vegetable* obj) { std::cout << "The object is a vegetable" << std::endl; }
};

我做:

std::vector<Food*> basket;
Fruit fruit = Fruit();
Vegetable vegetable = Vegetable();
basket.push_back(&fruit);
basket.push_back(&vegetable);

Child child = Child();

for (Food* food : basket)
{
    child.say(food);
}

我想要打印&#34;对象是水果&#34;然后&#34;对象是蔬菜&#34;,但它不起作用: 我收到错误消息:没有已知的转换参数1来自&#39; Food *&#39;到了水果*&#39;。

有没有办法做到这一点,如果可能的话不使用typeid,因为我听说它会导致开销。以下是在线编辑器中的代码:cpp.sh/27ekc

1 个答案:

答案 0 :(得分:2)

我认为对此的适当解决方案如下:

class Food 
{
public:
    virtual ~Food() = default;
    virtual void say() const;
};
class Fruit : public Food 
{
public:
    void say() const override { std::cout << "The object is a fruit" << std::endl; }
};
class Vegetable : public Food 
{
public:
    void say() const override { std::cout << "The object is a vegetable" << std::endl; }
};

class Parent
{
public:
    virtual ~Parent() = default;
    virtual void say(const Food& obj) const { obj.say(); }
};

class Child : public Parent {};

int main()
{
    std::vector<Food*> basket;
    Fruit fruit = Fruit();
    Vegetable vegetable = Vegetable();
    basket.push_back(&fruit);
    basket.push_back(&vegetable);

    Child child = Child();

    for (const Food* food : basket)
    {
        child.say(*food);
    }
}

编辑: 根据您的评论,它取决于您对健康的意义。 我将其解释为以下几点:

class Food 
{
public:
    virtual ~Food() = default;
    virtual void say() const;
    virtual int health() const;
};
class Fruit : public Food 
{
public:
    void say() const override { std::cout << "The object is a fruit" << std::endl; }
    int health() const override { return 5; }
};
class Vegetable : public Food 
{
public:
    void say() const override { std::cout << "The object is a vegetable" << std::endl; }
    int health() const override { return 10; }
};

class Parent
{
public:
    virtual ~Parent() = default;
    virtual void say(const Food& obj) const { obj.say(); }
};

class Child : public Parent 
{
    int health;

public:
    void eat(const Food& obj) { health += obj.health(); }
};

int main()
{
    std::vector<Food*> basket;
    Fruit fruit = Fruit();
    Vegetable vegetable = Vegetable();
    basket.push_back(&fruit);
    basket.push_back(&vegetable);

    Child child = Child();

    for (const Food* food : basket)
    {
        child.say(*food);
        child.eat(*food);
    }
}

有很多不同的方法可以实现这一目标。