c++的virtual和override作用及说明
作者:游戏猫
这篇文章主要介绍了c++的virtual和override作用及说明,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
一、概述
c++的virtual提供了运行时的多态,可以用基类的指针调用子类对象的函数,通过override可以强制要求基类有对应的虚函数。
二、测试代码
#pragma once #include <stdio.h> class Base { public: void A_1() { printf("Base::A_1\n"); }; virtual void A_2() { printf("Base::A_2\n"); } virtual void A_3() { printf("Base::A_3\n"); } virtual void A_4() { printf("Base::A_4\n"); } void A_5() { printf("Base::A_5\n"); } }; class Drived : public Base { public: void A_1() //覆盖了基类的函数,用基类指针调用时调用到的时基类的A_1,用子类指针调用时调用到的时子类的A_1 { printf("Drived::A_1\n"); }; virtual void A_2() //用基类或子类指针都调用到的是子类的A_2,之类的virtual说明的是是子类的A_2还可以被virtual { printf("Drived::A_2\n"); } void A_3() //用基类或子类指针都调用到的是子类的A_2 { printf("Drived::A_3\n"); } virtual void A_4() override //子类加上override,如果基类没有对应virtual函数就会编译错误。避免拼错和记错没有重写基类函数 { printf("Drived::A_4\n"); } /* void A_5() override //编译错误 'Drived::A_5': method with override specifier 'override' did not override any base class methods { printf("Drived::A_5\n"); } */ }; class Drived2 : public Drived { public: void A_2() override { printf("Drived2::A_2\n"); } void A_3() override//用基类或子类指针都调用到的是子类的A_2 { printf("Drived2::A_3\n"); } }; class VirtualTest { public: void DoTest() { Drived *drived = new Drived(); Base *base = drived; base->A_1(); drived->A_1(); printf("\n"); base->A_2(); drived->A_2(); printf("\n"); base->A_3(); drived->A_3(); printf("\n"); base->A_4(); drived->A_4(); printf("\n"); Drived2 *drived2 = new Drived2(); base = drived2; drived = drived2; base->A_2(); drived->A_2(); drived2->A_2(); printf("\n"); base->A_3(); drived->A_3(); drived2->A_3(); } };
三、输出
Base::A_1
Drived::A_1Drived::A_2
Drived::A_2Drived::A_3
Drived::A_3Drived::A_4
Drived::A_4Drived2::A_2
Drived2::A_2
Drived2::A_2Drived2::A_3
Drived2::A_3
Drived2::A_3
四、总结
1、基类函数没加virtual,子类有相同函数,实现的是覆盖。用基类指针调用时,调用到的是基类的函数;用子类指针调用时,调用到的是子类的函数。
2、基类函数加了virtual时,实现的时重写。用基类指针或子类指针调用时,调用到的都是子类的函数。
3、函数加上override,强制要求基本相同函数需要是虚函数,否则会编译报错。
4、子类的virtual可加可不加,建议加override不加virtual。
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。