在玩逻辑转换时我注意到了一件奇怪的事情.这是我的代码:
#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后它工作正常,但我不明白为什么.有人能帮我吗 ?