使用默认参数解析虚拟功能

编程入门 行业动态 更新时间:2024-10-10 04:23:08
本文介绍了使用默认参数解析虚拟功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

My understanding was default parameter functions were resolved during compile time using function overloading. Virtual functions were then resolved during runtime using function overriding.

但是发生的是一团糟.函数解析实际上是如何发生的?

But what is happening is a mess. How does the function resolution actually happen here?

推荐答案

实际上,编译器会看到您的代码,如下所示:(实际上不存在 display()方法,但是解析方式类似)

Your code is actually seen by the compiler like this: (The display() method is not actually there, but the resolving works in similar way)

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(),它会调用虚拟函数.更严格地说:解析默认参数就像使用no-arg非虚拟方法一样-根据变量的类型(而不是对象的实际类型),但是代码是根据虚拟对象类型执行的,因为它是虚拟方法:

Now you should understand what happens. You are calling the non-virtual display() which calls the virtual function. In more strict words: the default argument is resolved just like if the no-arg non-virtual method was there - by the type of the variable (not by the actual type of the object), but the code gets executed according to real object type, because it is virtual method:

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

更多推荐

使用默认参数解析虚拟功能

本文发布于:2023-06-02 19:32:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/457429.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:参数   功能

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!