zoukankan      html  css  js  c++  java
  • virtual作用:实现多接口

    virtual修饰的函数可以在派生的类中重新定义,可以通过动态分配对象的基类指针实现多借口。

     
    例:
    #include<iostream>
    
    using namespace std;
    
    class A
    {
        public:
            A(int x=0):t(x){}
            virtual int f()
            {
                return t;   
            }
        private:
            int t;
    };
    
    class B:public A
    {
        public:
           B(int x=0,int y=0):A(x),t(y){}
           int f()
           {
               return 10*t;   
           }
        private:
            int t;    
    };
    
    int main()
    {
        B b(3,2);
        A *tmp=&b;
        cout<<tmp->A::f()<<endl;
        cout<<tmp->f()<<endl;
        system("pause");
        return 0;
    }

    若基类去掉virtual修饰,那么将不具有多接口的作用!
     
    #include<iostream>
    
    using namespace std;
    
    class A
    {
        public:
            A(int x=0):t(x){}
            int f()
            {
                return t;   
            }
        private:
            int t;
    };
    
    class B:public A
    {
        public:
           B(int x=0,int y=0):A(x),t(y){}
           int f()
           {
               return 10*t;   
           }
        private:
            int t;    
    };
    
    int main()
    {
        B b(3,2);
        A *tmp=&b;
        cout<<tmp->A::f()<<endl;
        cout<<tmp->f()<<endl;
        system("pause");
        return 0;
    }

     

  • 相关阅读:
    BPF and eBPF linux
    o-sync-and-o-direct
    linux performance test
    iostat
    MYSQL IO innodb-buffer-pool
    MYSQL file types redo log
    read pread write pwrite open
    CORE DUMP
    linux kernel的中断子系统 softirq
    linux KERNEL 问题
  • 原文地址:https://www.cnblogs.com/icfnight/p/3239063.html
Copyright © 2011-2022 走看看