gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 01:55:40 25 4
gpt4 key购买 nike

我有两个专门的对象:

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

我希望它打印“对象是水果”,然后是“对象是蔬菜”,但它不起作用:我收到错误消息:参数 1 没有从“Food*”到“Fruit*”的已知转换。

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

最佳答案

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

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

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

关于c++ - 有没有办法专门化继承对象的一般方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41304907/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com