C专家编程 第11章 你懂得C,所以C++不再话下 11.16 新奇玩意儿---多态

发布于:2022-12-20 ⋅ 阅读:(294) ⋅ 点赞:(0)

    新奇玩意儿---多态
    它可使派生类的成员函数优先于基类的同名函数获得调用,但如果派生类对虚拟函数未曾定制,也可以调用基类的成员函数。有时候,成员函数在编译时并不知道它是作用于本类的对象还是派生于本类的子类对象。多态必须保证这种情况能够正确地工作。

    int main() {
        Apple apple;
        Fruit orange;
        Fruit *p;
        p = &apple;
        p->peel();
        p = &orange;
        p->peel();
    } 
    在运行时,结果将会是:
    peeling an apple
    peeling a base class fruit

    深入思考---多态和interposing有相似之处。
    多态和interposing都允许用一个标记符来命名多个函数。interposing是一种多少有些笨拙的方式,它在编译时把所有用该标识符命名的函数都绑定到一个函数中。多态则显得精巧一些,它可以在运行时根据对象的类属关系决定调用那个函数。 

    /*
    ** operator overload.
    */
    #include <stdio.h>
    #include <stdlib.h>
    class Fruit {
        public:
            Fruit( int i, int j );
            virtual void peel( void );
            void slice( void );
            void juice( void );
            virtual ~Fruit( void );
        private: int weight, calories_per_oz;
    };
    
    class Apple : public Fruit{
        public:
            Apple( int i, int j );
            void peel( void );
            /*void make_candy_apple(float weight);*/
            ~Apple( void );
    };
    
    int main( void ){
        Fruit *fruit = new Apple( 1, 2 );
        fruit->Fruit::peel();
        fruit->peel();
        delete fruit;
    
        return EXIT_SUCCESS;
    }
    
    Fruit::Fruit( int i, int j ){
        printf( "fruit constructor is called!\n" );
        weight = i;
        this->calories_per_oz = j;
    }
    
    void Fruit::peel( void ){
        printf( "fruit peel!\n" );
    }
    
    void Fruit::slice( void ){
        printf( "in slice!\n" );
    }
    
    void Fruit::juice( void ){
        printf( "in juice!\n" );
    }
    
    Fruit::~Fruit( void ){
        printf( "fruit destructor is called!\n" );
    }
    
    Apple::Apple( int i, int j ) : Fruit( i, j ){
        printf( "apple constructor is called!\n" );
    }
    
    void Apple::peel( void ){
        printf( "apple peel!\n" );
    }
    
    Apple::~Apple( void ){
        printf( "apple destructor is called!\n" );
    }
输出:


网站公告

今日签到

点亮在社区的每一天
去签到

热门文章