欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

什么是虚函数?什么是纯虚函数?两者有何区别?

最编程 2024-05-23 09:23:49
...
#include<iostream> using namespace std; //含有虚函数的基类 class Base { public: virtual void vir_func() { cout << "virtual function, this is base class" << endl; } void func() { cout << "normal function, this is base class" << endl; } }; //派生类A class A : public Base { public: virtual void vir_func() { cout << "virtual function, this is A class" << endl; } void func() { cout << "normal function, this is A class" << endl; } }; //派生类B class B : public Base { public: virtual void vir_func() { cout << "virtual function, this is B class" << endl; } void func() { cout << "normal function, this is B class" << endl; } }; int main(int argc, char const *argv[]) { //多态 Base* base = new Base; Base* a = new A; Base* b = new B; //访问基类的func() base->func(); a->func(); b->func(); cout << "####################" << endl; //访问派生类的func() base->vir_func(); a->vir_func(); b->vir_func(); cout << "####################" << endl; ((A*)b)->vir_func(); ((A*)b)->func(); return 0; }

推荐阅读