C&C++   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了c – 使用默认参数解析虚函数大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
参见英文答案 > Can virtual functions have default parameters?6个
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

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

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

解决方法

您的代码实际上是由编译器看到的,如下所示:
(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); }
};

现在您应该了解会发生什么.您正在调用调用函数的非虚拟显示().用更严格的话说:认参数的解析就像没有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)
}

大佬总结

以上是大佬教程为你收集整理的c – 使用默认参数解析虚函数全部内容,希望文章能够帮你解决c – 使用默认参数解析虚函数所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。