使用默认参数解析虚函数

cpp*_*der 6 c++ virtual-functions overload-resolution

header.h

#include <iostream>
using namespace std;
class A
{
    public:
        virtual void display(int i=5) { cout<< "Base::" << i << endl; }
};

class B : public A
{
    public:
        void display(int i=9) { cout<< "Derived::" << i << endl; }
};  
Run Code Online (Sandbox Code Playgroud)

source.h

#include <iostream>
#include "header.h"
using namespace std;
int main()
{
    A * a = new B();
    a->display();

    A* aa = new A();
    aa->display();

    B* bb = new B();
    bb->display();
}  
Run Code Online (Sandbox Code Playgroud)

产量

Derived::5
Base::5
Derived::9  
Run Code Online (Sandbox Code Playgroud)

我的理解是使用函数重载在编译期间解析了默认参数函数.然后在运行时使用函数重写解析虚函数.

但正在发生的事情是一团糟.
功能解析如何实际发生在这里?

0xF*_*0xF 7

默认参数没有多态性.它们在编译时解析.

A::display有默认参数等于5. B::display具有默认参数等于9,这是唯一的类型a,aa,bb变量的事项.

在多态方法中使用不同的默认参数是令人困惑的,应该避免.

  • @StefanoF因为`a`是'A*'类型,而`bb`是'B*`类型.因此,`a-> display()`使用来自`class A`的声明,而`bb-> display()`使用`class B'中的声明 (2认同)

fir*_*rda 7

您的代码实际上是由编译器看到的:(
display()方法实际上并不存在,但解析以类似的方式工作)

class A
{
public:
    virtual void display(int i) { cout<< "Base::" << i << endl; }
    void display() { display(5); }
};

class B : public A
{
public:
    void display(int i) override { cout<< "Derived::" << i << endl; }
    void display() { display(9); }
};
Run Code Online (Sandbox Code Playgroud)

现在您应该了解会发生什么.您正在调用非虚拟display()调用虚拟函数.用更严格的话说:默认参数的解析就像没有arg非虚方法那样 - 通过变量的类型(不是由对象的实际类型),但是代码是根据真实对象执行的类型,因为它是虚方法:

int main()
{
    A * a = new B(); // type of a is A*   real type is B
    a->display();    // calls A::display() which calls B::display(5)

    A* aa = new A(); // type of aa is A*  real type is A
    aa->display();   // calls A::display() which calls A::display(5)

    B* bb = new B(); // type of bb is B*  real type is B
    bb->display();   // calls B::display() which calls B::display(9)
}  
Run Code Online (Sandbox Code Playgroud)

  • 嗯,这很复杂。 (2认同)
  • 请注意,firda的代码只是为了更好地理解幕后发生的事情.编译器并没有真正将您的代码转换为此代码. (2认同)

And*_*ter 6

这种行为是在指定的章8.3.6:默认参数的编程语言- C++(ISO/IEC 14882:2003(E)) :

虚函数调用(10.3)使用由指针的静态类型或表示对象的引用确定的虚函数的声明中的默认参数