首页 > 解决方案 > 在从抽象类继承的类中使用子类对象作为参数

问题描述

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

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 类中的同时解决我的问题?

标签: c++classvirtual-functions

解决方案


您使用的演员阵容错误。

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并不会神奇地将inta 变成 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;
}

推荐阅读