繁体   English   中英

没有调用c ++虚方法

[英]c++ virtual method isn't being called

我在头文件中声明了两个c ++类。 基数声明一个虚方法,第二个类重写它。 实现在.cpp文件中。

代码非常简单

void DefendProperty::apply(Queue<Defend*>* defendQueue, 
const Tool* toolSource, const Actor* actorSource, const Actor* defender) {
    cout << "BASE" << endl;
}

void DefendPropertyPhysical::apply(Queue<Defend*>* defendQueue, 
Tool* toolSource, const Actor* actorSource, const Actor* defender) {
    cout << "CORRECT" << endl;
    defendQueue->enqueue(new Defend(
        DefendTypePhysical::TYPE, 
        new DamageValuesPhysical(
        getRandomDouble(minDamageReduction, maxDamageReduction))
    ));
}

关键是当我将类实例化为B时,它输出BASE,而不是CORRECT。 我不知道此时发生了什么。

这些类存储在没有apply方法的基本ToolProperty类型中。 当它们被调用时,它们使用dynamic_cast被类型转换为DefendProperty类型。

dynamic_cast<DamageProperty*>(node->value)->apply(damageQueue, toolSource, actorSource);

任何帮助,将不胜感激

派生类中方法的签名与基类中的签名不同。 (一个是const Tool* ,另一个是非const Tool*

由于签名不同,派生类的方法不会覆盖基类的方法,而是声明一个新的,不相关的方法。

您的功能有不同的签名。 查看“toolSource”的类型。 你的第二个不是第一个的重写,而是一个重载。

编译器几乎从不警告你的常见错误。 我不知道那个做了什么。

顺便说一下,没有理由使用动态强制转换,如果你要在指针上使用它而不检查结果。

  1. 确保功能签名相同。 toolSource不const的DefendPropertyPhysical 如果签名不匹配,c ++编译器将不会假设您犯了错误,它只会假设您声明该方法的新重载。 C ++ 11的显式覆盖有助于此。

  2. 确保DefendProperty::apply在标题中标记为virtual

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM