c++ - 在从抽象类继承的类中使用子类对象作为参数
问题描述
我正在创建两个类。第一个是抽象基类,第二个继承自第一个。
struct Animal
{
bool is_multicellular;
int children;
Animal() {
this->is_multicellular = true;
this->children = 0;
}
virtual Animal& attempt_to_mate(Animal&) = 0;
};
struct Bear : Animal
{
bool has_fur;
bool wants_to_mate;
Bear() : Animal() {
this->has_fur = true;
}
Animal& attempt_to_mate(Animal &bear) override {
bear = dynamic_cast<Bear&>(bear);
if (bear.wants_to_mate) {
this->children ++;
}
return bear;
}
};
int main()
{
Bear bear1;
bear1.wants_to_mate = true;
Bear bear2;
bear2.attempt_to_mate(bear1);
}
当我编译时,编译器告诉我
main.cpp: In member function ‘virtual Animal& Bear::attempt_to_mate(Animal&)’:
main.cpp:32:18: error: ‘struct Animal’ has no member named ‘wants_to_mate’; did you mean ‘attempt_to_mate’?
if (bear.wants_to_mate) {
^~~~~~~~~~~~~
虽然 Animal 没有变量wants_to_mate
,但 Bear 有,我正在尝试将动物强制转换为 Bear。解决我的问题的一种方法是将变量移动wants_to_mate
到 Animal 类。有没有办法在将变量保留在 Bear 类中的同时解决我的问题?
解决方案
您使用的演员阵容错误。
Animal& attempt_to_mate(Animal &bear) override {
bear = dynamic_cast<Bear&>(bear);
if (bear.wants_to_mate) {
this->children ++;
}
return bear;
}
bear
是指动物。您可以为它分配对 a 的引用Bear
,但这不会将其变成对熊的引用。就像将 a 分配double
给 anint
并不会神奇地将int
a 变成 a double
:
int x = 5;
x = static_cast<double>(x) + 0.5;
std::cout << x; // x is still 5
而是声明对 a 的引用Bear
并使用它:
Animal& attempt_to_mate(Animal &bear) override {
Bear& b = dynamic_cast<Bear&>(bear);
if (b.wants_to_mate) {
this->children ++;
}
return bear;
}
推荐阅读
- javascript - 为什么 data.map 不是函数?
- django - Django ImageField 不验证图像
- javascript - 如何将字符串转换为模板字符串
- laravel - 如何验证 Laravel 中的“用户名”字段是否包含字母、数字、下划线和破折号?
- node.js - 构建一个可扩展的网站抓取系统
- swiftui - 格式化绑定
那在我的 TextField 中 - sql - 运行访问查询:“From 子句中的语法错误”错误
- python - Airflow HttpSensor 使用默认主机
- python - 在 Django 中使用 Markdown2
- wordpress - WooCommerce 错误:我们无法处理您的订单,请重试