使用子 class 对象作为 class 继承自抽象 class 的参数

Using a subclass object as a parameter in a class inheriting from an abstract class

我正在创建两个 classes。第一个是抽象基础class,第二个继承自第一个

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 有,我正在尝试将 animal 转换为 bear。解决我的问题的一种方法是将变量 wants_to_mate 移动到动物 class。有什么方法可以解决我的问题,同时将变量保留在 Bear class?

您使用的转换有误。

Animal& attempt_to_mate(Animal &bear) override {
    bear = dynamic_cast<Bear&>(bear);
    if (bear.wants_to_mate) {
        this->children ++;
    }
    return bear;
}

bear 指的是动物。您可以将对 Bear 的引用分配给它,但这不会将它变成对熊的引用。就像将 double 分配给 int 不会神奇地将 int 变成 double:

 int x = 5;
 x = static_cast<double>(x) + 0.5;
 std::cout << x;  // x is still 5

而是声明对 Bear 的引用并使用它:

Animal& attempt_to_mate(Animal &bear) override {
    Bear& b = dynamic_cast<Bear&>(bear);
    if (b.wants_to_mate) {
        this->children ++;
    }
    return bear;
}