gpt4 book ai didi

C++ 虚拟常量函数

转载 作者:可可西里 更新时间:2023-11-01 18:41:26 26 4
gpt4 key购买 nike

给定以下片段,

class Base
{
public:
virtual void eval() const
{
std::cout<<"Base Const Eval\n";
}
};

class Derived:public Base
{
public:
void eval()
{
std::cout<<"Derived Non-Const Eval\n";
}
};

int main()
{

Derived d;
Base* pB=&d;

pB->eval(); //This will call the Base eval()

return 0;
}

为什么 pB->eval() 会调用 Base::eval()?

谢谢

最佳答案

在您的Derived 类中,eval 的原型(prototype)与Base 中虚函数的原型(prototype)不匹配。所以它不会覆盖虚函数。

Base::eval() const;
Derived::eval(); //No const.

如果您为 Derived::eval() 添加常量,您应该获得虚拟行为。

关于C++ 虚拟常量函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3827374/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com