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

    代码
    //  [7/29/2010 xuminghui]
    /*

     基类的指针指向派生类的对象,呼叫某函数Func时:
     1、若基类的Func非虚函数,调用基类的Func函数
     2、若基类的Func是虚函数
            1)、若派生类重写Func虚函数,自然呼叫派生类的Func;
            2)、若派生类未重写Func虚函数,则向基类方向追溯虚函数Func;
     3、以相同的指令呼叫不同的函数,这种性质成为多态(the ablility to assume many forms)
     编译器无法在编译时期判断到底调用哪一个函数,所以虚函数是后期绑定或动态(late binding)
     而编译期就可以判断并编码的,成为前期绑定,或者静态绑定static binding
     4、类中只要有一个纯虚函数,那么这个类就是抽象类,抽象类不可以实例化,只为多态目的而存在。
     抽象类中可以有非纯虚函数;抽象类的派生类必须改写抽象类的纯虚函数,否则这个派生类亦作抽象类。
     
    */
    #include 
    <iostream>
    using namespace std;

    class CShape
    {
    public://纯虚拟函数不需要定义其实际操作,它的存在只是为了在派生类中被重新定义
        virtual void display() = 0//{cout<<"Shape"<<endl;}//类中只要有一个纯虚函数,此类就是虚类
    };

    class CEllipse : public CShape
    {
    public:
        
    void display(){ cout << "Ellipse" << endl; }//虚拟函数派生下去仍然为虚拟函数,可以省略virtual关键字
    };

    class CCircle : public CEllipse
    {
        
    void display(){ cout << "Circle\n"; }
    };

    class CRect : public CShape
    {
        
    void display(){ cout << "Rect\n"; }
    };

    class CSquare : public CRect
    {
        
    void display(){ cout << "Square\n";}
    };

    void main2()
    {
        
    //CShape shape;
        CEllipse    ellipse;
        CCircle    circle;
        CRect    rect;
        CSquare    square;

        CShape 
    *shapes[4= 
        {
            
    &ellipse, &circle, &rect, &square
        };

        
    for (int i=0; i<4; i++)
        {
            shapes[i]
    ->display();
        }
    }


  • 相关阅读:
    Linux服务器上监控网络带宽命令
    boost编译很慢的解决方法
    python select poll
    python SocketServer
    boost implicit_cast
    函数名 函数名取地址 区别
    STL make_heap push_heap pop_heap sort_heap
    STL: fill,fill_n,generate,generate_n
    gcc __attribute__
    Linux命令 lsof使用
  • 原文地址:https://www.cnblogs.com/flaaash/p/1895123.html
Copyright © 2011-2022 走看看