zoukankan      html  css  js  c++  java
  • 【C++】虚函数和纯虚函数

    https://zhuanlan.zhihu.com/p/37331092  虚函数和纯虚函数

    https://blog.csdn.net/u012206617/article/details/87697667 虚函数和纯虚函数

    https://www.cnblogs.com/chwei2ch/p/10628608.html 虚函数和纯虚函数

    https://zhuanlan.zhihu.com/p/37340242 多态,讲得挺好

    虚函数例子:

    #include<iostream>
    
    using namespace std;
    
    int main()
    {
        class base
        {
        public:
            virtual void vir_func()
            {
                cout << "这是基类的虚函数" << endl;
            }
            void func()
            {
                cout << "这是基类的普通函数" << endl;
            }
        };
        class A :public base
        {
        public:
            virtual void vir_func()
            {
                cout << "这是类A的虚函数" << endl;
            }
            void func()
            {
                cout << "这是类A的普通函数" << endl;
            }
        };
        class B :public base
        {
        public:
            virtual void vir_func()
            {
                cout << "这是类B的虚函数" << endl;
            }
            void func()
            {
                cout << "这是类B的普通函数" << endl;
            }
        };
    
        base* Base = new base;
        base* a = new A;
        base* b = new B;
        Base->func();
        a->func();
        b->func();
        cout << "##########################" << endl;
        Base->vir_func();
        a->vir_func();
        b->vir_func();
        cout << "###########################" << endl;
        ((A*)b)->vir_func();
        ((A*)b)->func();
    
        return 0;
    }

    // 结论:当使用类的指针调用成员函数时,普通函数由指针类型决定,而虚函数由指针指向的实际类型决定。

    #include<iostream>
    using namespace std;
    
    class Virtualbase
    {
    public:
        virtual void Demon() = 0;
        virtual void Base()
        {
            cout << "这是基类(抽象类)的虚函数" << endl;
        }
    };
    
    class SubVirtual :public Virtualbase
    {
    public:
        void Demon()
        {
            cout << "这是子类实现的纯虚函数" << endl;
        }
        void Base()
        {
            cout << "这是子类的虚函数,复写了基类的虚函数方法" << endl;
        }
    };
    
    int main()
    {
        Virtualbase* inst = new SubVirtual;
        inst->Demon();
        inst->Base();
    
        return 0;
    }

  • 相关阅读:
    非空约束
    leetcode208
    leetcode207
    leetcode395
    leetcode116
    leetcode105
    leetcode131
    leetcode73
    leetcode200
    leetcode17
  • 原文地址:https://www.cnblogs.com/masbay/p/14198961.html
Copyright © 2011-2022 走看看