在阅读 vptr 和 vtable 概念时,我得到了这段精彩的代码,但我无法理解这里涉及的概念:
#include <iostream>
using namespace std;
class A
{
public:
virtual void foo(int x = 10)
{
cout << "base x : " << x << "\n";
}
virtual void bar()
{
cout << "base bar\n";
}
};
class B : public A
{
public:
virtual void foo(int x = 20)
{
cout << "derived x : " << x << "\n";
}
private:
virtual void bar()
{
cout << "derived bar\n";
}
};
class C : public B
{
};
int main()
{
A x; x.foo(); // x.foo(10);
B y; y.foo(); // x.foo(20);
A *p(&y);
p->foo();
}
现在我得到的输出是:
base x : 10
derived x : 20
derived x : 10
即使打印派生 x(即 B::foo()),默认参数也是基函数(即 A::foo())的参数,这怎么可能?
最佳答案
C++ 标准第 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.
在您的示例中,默认参数的评估是根据“p”的类型(即“A”)完成的。因此,默认参数的评估是从 A 的声明完成的,函数的调用是通过 vptr 表中的常规查找进行的。
关于c++ - 这里涉及函数调用和参数传递的概念,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29293180/