c++ - 这里涉及函数调用和参数传递的概念

标签 c++ overriding virtual-functions late-binding default-arguments

在阅读 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/

相关文章:

c++ - NodeJS 和 N-API

c++ - 仅编译 if-else 的一部分

c++ - 使用 FFMPEG/libavformat 查找 WebM 的持续时间/帧数

c++ - 我应该怎么做才能看到实际的静态和动态绑定(bind)? [C++]

c++ - 强制派生类覆盖至少一个虚函数

c++ - 在 C++ 中映射内部结构

javascript - 如何覆盖 print css 中的内联样式?

java - 在java中覆盖列表结果类型

class - 更改媒体时如何用另一个 CSS 类替换 CSS 类

c++ - 在构造和销毁期间调用虚拟方法