我对以下代码有一个奇怪的情况。请帮我澄清一下。
class B
{
public:
B();
virtual void print(int data=10)
{
cout << endl << "B--data=" << data;
}
};
class D:public B
{
public:
D();
void print(int data=20)
{
cout << endl << "D--data=" << data;
}
};
int main()
{
B *bp = new D();
bp->print();
return 0;
}
关于我期望的输出
[ D--data=20 ]
但实际上是这样的
[ D--data=10 ]
请帮忙。这对你来说似乎很明显,但我不知道内部机制。
最佳答案
标准说 (8.3.6.10):
A virtual function call (10.3) uses the default arguments in the declaration of the virtual function determined by the static type of the pointer or reference denoting the object. An overriding function in a derived class does not acquire default arguments from the function it overrides.
这意味着,由于您通过 B
类型的指针调用 print
,它使用 B::print
的默认参数。
https://stackoverflow.com/questions/6464404/