这里涉及函数调用和参数传递的概念
concept involved here in function calling and argument passing
在阅读 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())的参数,这怎么可能?
默认参数好像是在编译时解析的。参见 here and here。
The default values that are used will be those defined in the static (compile-time) type. So if you were to change the default parameters in an override, but you called the function through a base class pointer or reference, the default values in the base would be used.
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 table.
中的常规查找进行的
在阅读 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())的参数,这怎么可能?
默认参数好像是在编译时解析的。参见 here and here。
The default values that are used will be those defined in the static (compile-time) type. So if you were to change the default parameters in an override, but you called the function through a base class pointer or reference, the default values in the base would be used.
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 table.
中的常规查找进行的