作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有两个专门的对象:
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/
我是一名优秀的程序员,十分优秀!