开发者

c++的virtual和override作用及说明

开发者 https://www.devze.com 2022-12-02 12:34 出处:网络 作者: 游戏猫
目录一、概述二、测试代码三、输出四、总结一、概述 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//用基类或子类指针都调用www.devze.com到的是子类的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_4javascript();
  drived->A_4();
  printf("\n");

  Drived2 *drived2 = new开发者_C入门 Drived2();
  base = drived2;
  drived = drived2;
  
  base->A_2();
  drived->A_2();
  drived2->A_2();
  printf("\n");

  base->A_3();
  drived->A_3();
  drived2-&g编程客栈t;A_3();

 }
};

三、输出

Base::A_1

Drived::A_1

Drived::A_2

Drived::A_2

Drived::A_3

Drived::A_3

Drived::A_4

Drived::A_4

Drphpived2::A_2

Drived2::A_2

Drived2::A_2

Drived2::A_3

Drived2::A_3

Drived2::A_3

四、总结

1、基类函数没加virtual,子类有相同函数,实现的是覆盖。用基类指针调用时,调用到的是基类的函数;用子类指针调用时,调用到的是子类的函数。

2、基类函数加了virtual时,实现的时重写。用基类指针或子类指针调用时,调用到的都是子类的函数。

3、函数加上override,强制要求基本相同函数需要是虚函数,否则会编译报错。

4、子类的virtual可加可不加,建议加override不加virtual。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号