017_linuxC++之_多态的引入

多态:一种接口,多种方法(同一种调用方法,根据不同的对象,调用不同类中的函数)
静态联编:非虚函数,在编译时确定好
动态联编: 1. 对象里有指针,指向虚函数表
      2. 通过指针,找到表,调用虚函数
      3. 图二
      4. virtual来定义为虚函数
(一)首先我们来看静态联编,非多态的程序

#include <iostream>
#include <string.h>
#include <unistd.h>

using namespace std;

class Human {
public:
    void eating(void) { cout<<"use hand to eat"<<endl; }
};

class Englishman : public Human {
public:
    void eating(void) { cout<<"use knife to eat"<<endl; }
};


class Chinese : public Human {
public:
    void eating(void) { cout<<"use chopsticks to eat"<<endl; }
};

void test_eating(Human& h)
{
    h.eating();
}

int main(int argc, char **argv)
{
    Human h;
    Englishman e;
    Chinese c;

    test_eating(h);
    test_eating(e);
    test_eating(c);

    return 0;
}

运行结果,调用的全部是Human中的,并不是我们想要的,因为这里是静态编译进去了,也就是说程序在编译时候就已经确定好就调用Human中的
在这里插入图片描述

(二)动态编译,实现多态,在类中定义时候增加virtual来实现这个函数为虚函数

#include <iostream>
#include <string.h>
#include <unistd.h>

using namespace std;

class Human {
public:
    virtual void eating(void) { cout<<"use hand to eat"<<endl; }
};

class Englishman : public Human {
public:
    virtual void eating(void) { cout<<"use knife to eat"<<endl; }
};


class Chinese : public Human {
public:
    virtual void eating(void) { cout<<"use chopsticks to eat"<<endl; }
};

void test_eating(Human& h)
{
    h.eating();
}

int main(int argc, char **argv)
{
    Human h;
    Englishman e;
    Chinese c;

    test_eating(h);
    test_eating(e);
    test_eating(c);

    return 0;
}

运行结果,就实现了同一接口,不同调用的方法了
在这里插入图片描述

(三)更多具体的,,,,,,,
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值