问题描述
我正在创建两个类。第一个是抽象基类,第二个继承自第一个。
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 类中?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)