问题描述
我对以下代码有一个奇怪的情况。请帮我澄清。
class B
{
public:
B ();
virtual void print(int data = 10)
{
cout< endl<< B-data =<数据;
}
};
class D:public B
{
public:
D();
void print(int data = 20)
{
cout< endl<< D-data =<数据;
}
};
int main()
{
B * bp = new D();
bp-> print();
return 0;
}
关于我预期的输出
[D - data = 20]
但实际上是
[D - data = 10]
pre>
请帮助。它可能看起来很明显,但我不知道内部机制。
解决方案默认参数是完全编译时功能。也就是说在编译时执行代替缺少参数的缺省参数的替换。因此,很明显,成员函数的默认参数机制不能依赖于对象的动态(即运行时)类型。它始终取决于对象的 static (即编译时)类型。
您在代码示例中编写的调用会立即被编译器解释为
bp-> print(10)
不管别的什么。I have a strange situation over the following code. Please help me to get it clarified.
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; }
Regarding the output I expected
[ D--data=20 ]
But in practical it is
[ D--data=10 ]
Please help. It may seem obvious for you but I am not aware of the internal mechanism.
解决方案Default arguments are entirely compile-time feature. I.e. the substitution of default arguments in place of missing arguments is performed at compile time. For this reason, obviously, there's no way the default argument mechanism for member functions can depend on the dynamic (i.e. run-time) type of the object. It always depends on static (i.e. compile-time) type of the object.
The call you wrote in your code sample is immediately interpreted by the compiler as
bp->print(10)
regardless of anything else.这篇关于虚函数默认参数行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!