zoukankan      html  css  js  c++  java
  • c++ 一般虚函数

    类图:

    代码:

    #include <iostream>
    using namespace std;
    class CFather          //父类
    {
    public:
        virtual void display() const { cout<<"CFather::display()"<<endl;}  //一般虚
    };
    class CSon:public CFather       //子类
    {
    public:
        void display() const { cout<<"CSon::display()"<<endl;}
        void display(int iSonRec){ cout<<"CSon receive one number:"<<iSonRec<<endl;}//形参个数上的区别
    };
    class CGrandSon:public CSon      //
    {
    public:
        void display() const { cout<<"CGrandSon::display()"<<endl;}
        
    };
    void show(CFather *ptr)          //一般函数,父方法show
    {
        ptr->display();
    }
    void showson(CSon *ptr)              //一般函数,子方法show
    {
        ptr->display();
    }
    int main()
    {
        CFather father;            //父实现
        CSon son;                //子实现
        CGrandSon grandson;        //孙实现
        //以下传参,一般虚函数的传递性
        show(&father);
        show(&son);
        show(&grandson);
        showson(&grandson);
        //有参数区别
        son.display(1099);
    
        
    
        getchar();
        return 0;
    
    }

    结果:

    总结:派生类没有显式给出虚函数,判断派生类的一个函数成员是否为虚函数:

    1,该函数是否与基类的虚函数同名

    2,该函数是否与基类的虚函数有相同的参数个数及参数对应类型

    3,该函数是否与基类的虚函数有相同的返回值或者满足“c++ 基类,派生类的类型兼容性”的指针,引用(别名)的返回值。

    满足以上条件,自动确定为虚函数,且覆盖了基类的虚函数,还会隐藏基类同名函数的所有其他重载。

    这时,"C++派生类成员访问作用域".作用域符行之有效。

  • 相关阅读:
    日期转换DateTime
    linux 常用命令
    springcloud集成 xxl-job
    maven-阿里云镜像
    mysql 8.0+忘记root密码-linux
    java注解与自定义注解
    mysql联合索引的生效规则
    Maven常用命令及其作用、常见问题、常用命令使用场景举例
    反射的理解
    VirtualBox创建centos
  • 原文地址:https://www.cnblogs.com/liunnis/p/4464860.html
Copyright © 2011-2022 走看看