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

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

    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" );
    }
输出:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

weixin_40186813

你的能量无可限量。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值