c++ - 静态基类型和动态派生类型的输出

标签 c++ inheritance polymorphism overriding dynamic-binding

main 下面输出的答案是“derived class display with i=10”,但我不明白为什么?该函数肯定是在基类型上调用的吗?

在这里确定答案的思考过程是什么?

class base
{
  public:
         virtual void display(int i = 10)
         {
           cout<<"Base class display with i = "<<i<<endl;
         }

};

class derived : public base
{
  public:
          void display(int i = 20)
         {
           cout<<"Derived class display with i = "<< i <<endl;
         }

};

int main(int argc, char *argv[])
{
     base *bptr = new derived;
     bptr->display();

      return 0;
}

最佳答案

看看Can virtual functions have default parameters? :

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.

因此,bptr->display(); 调用了 display 的派生版本,但使用了 base 的参数,静态类型指针 bptr

这是因为参数的默认值必须在编译时确定,而动态绑定(bind)则推迟到运行时。在同一虚拟的基础版本和派生版本中使用不同的默认参数几乎肯定会造成麻烦。当virtual是通过引用或者指向base的指针调用的时候很可能会出现问题,但是执行的版本是derived定义的版本。在这种情况下,为虚拟的基本版本定义的默认参数将传递给派生版本,派生版本是使用不同的默认参数定义的。

关于c++ - 静态基类型和动态派生类型的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18066846/

相关文章:

c++ - Dynamic_cast 不需要执行运行时检查吗?

c++ - 在 C++ 中签署/认证文本文件的最简单方法?

c++ - 如何在 Windows 8 和 10 中枚举已安装的 StoreApps 及其 ID

c++ - 多线 Controller 降低高度

C++ 模板和继承

objective-c - 类方法也被继承了吗?

无继承的 OOP 重用 : How "real-world" practical is this?

c++ - 如何从 masm 引用外部 C++ 函数?

java - 多态性 - 歧义错误

c++ - 对象的底层类型是如何在运行时确定的?