【问题标题】:Resolution of virtual function with default parameters [duplicate]使用默认参数解析虚函数[重复]
【发布时间】:2014-09-23 12:00:05
【问题描述】:

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; }
};  

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();
}  

输出

Derived::5
Base::5
Derived::9  

我的理解是在编译时使用函数重载解决了默认参数函数。然后在运行时使用函数覆盖来解析虚函数。

但是发生的事情是一团糟。
这里的函数解析实际上是如何发生的?

【问题讨论】:

  • Default argument resolution is based on the static type of the object through which you call the function(即基于指针类型)。 social.msdn.microsoft.com/Forums/en-US/…
  • 请注意,您可以通过使用另一个不带参数的虚拟函数重载虚拟函数来解决此问题,该虚拟函数“转发”到带有参数的虚拟函数。喜欢:在 Base virtual void display() { display(9); } 和 Derived void display() { display(5); }

标签: c++ virtual-functions overload-resolution


【解决方案1】:

您的代码实际上是这样被编译器看到的:
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); }
};

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

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)
}  

【讨论】:

  • 哦,这正是我要找的。嘿,但是Derived::5 是如何打印的?应该是Base::5
  • 当您在(动态)类型B 的对象上调用a-&gt;display(); 时,它会调用display();,即非虚拟重载 display()调用display(5);,然后实际上解析为B::display(5)。在原始代码中也发生了类似的事情。它不是附加的非虚拟函数,而是在静态类型上解析的默认参数。
  • 嗯,这很复杂。
  • 请注意,firda 的代码只是为了更好地理解幕后发生的事情的演示。编译器并没有真正将你的代码翻译成这个。
  • @leemes 我想,那么问带默认参数的函数是如何解析的又是另外一个问题了?
【解决方案2】:

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

A::display 的默认参数等于 5。 B::display 的默认参数等于 9。 只有aaabb 变量的类型很重要。

在多态方法中使用不同的默认参数会造成混淆,应该避免。

【讨论】:

  • 对不起,我不明白:为什么a-&gt;display() 显示Derived::5bb-&gt;display() 显示Derived::9?它们的定义方式完全相同...
  • @StefanoF 因为aA* 类型,而bbB* 类型。因此,a-&gt;display() 使用来自class A 的声明,而bb-&gt;display() 使用来自class B 的声明
【解决方案3】:

此行为在第 8.3.6 章:Programming languages — C++ (ISO/IEC 14882:2003(E)) 中的默认参数中指定:

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

【讨论】:

    猜你喜欢
    • 2014-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-23
    • 2012-07-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多