gpt4 book ai didi

c++ - 虚函数默认参数行为

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:21:18 27 4
gpt4 key购买 nike

我对以下代码有一个奇怪的情况。请帮我澄清一下。

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 的默认参数。

关于c++ - 虚函数默认参数行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44835816/

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