为什么选择了重载基类值的默认参数值,而不是执行的派生方法中指定的默认值

Krz*_*ski 3 c++

在玩逻辑转换时我注意到了一件奇怪的事情.这是我的代码:

#include <iostream>

using namespace std;
class C
{
public:
    virtual int shift(int n = 2) const { return n << 2; }
};
class D
    : public C
{
public:
    int shift(int n = 1) const { return n << 5; }
};
int main()
{
    const D d;
    const C *c = &d;
    cout << c->shift() << endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

程序返回64,因此从类C中获取值n = 2,从类D中获取函数的主体.

从函数中删除const后它工作正常,但我不明白为什么.有人能帮我吗 ?

Che*_*Alf 6

默认参数值基于静态类型(编译时已知的类型).

虚函数实现的选择取决于对象在运行时的派生类型最多,即动态类型.