大佬教程收集整理的这篇文章主要介绍了c – 使用默认参数解析虚函数,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
#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
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,请注明来意。