14周-初体验多态性

#include <iostream>
using namespace std;
class Vehicle  //交通工具
{
public:
    void run() const
    {
        cout << "run a vehicle. "<<endl;
    }
};
class Car: public Vehicle  //汽车
{
public:
    void run() const
    {
        cout << "run a car. "<<endl;
    }
};
class Airplane: public Vehicle  //飞机
{
public:
    void run() const
    {
        cout << "run a airplane. "<<endl;
    }
};
int main()
{
    cout<<"(a) 直接用对象访问成员函数: "<<endl;
    Vehicle v;
    v.run();
    Car car;
    Airplane airplane;
    car.run();
    airplane.run();
    cout<<"(b)用指向基类的指针访问成员函数: "<<endl;
    Vehicle *vp;
    vp=&car;
    vp->run();
    vp=&airplane;
    vp->run();
    return 0;
}


当基类的指针指向派生类时,用指针调用同名成员函数,执行的是基类的成员函数

#include <iostream>
using namespace std;
class Vehicle {
public:
    virtual void run() const { cout << "run a vehicle. "<<endl; } //(2) run()为虚函数
};
class Car: public Vehicle  //汽车
{
public:
    void run() const
    {
        cout << "run a car. "<<endl;
    }
};
class Airplane: public Vehicle  //飞机
{
public:
    void run() const
    {
        cout << "run a airplane. "<<endl;
    }
};
int main()
{
    cout<<"(a) 直接用对象访问成员函数: "<<endl;
    Vehicle v;
    v.run();
    Car car;
    Airplane airplane;
    car.run();
    airplane.run();
    cout<<"(b)用指向基类的指针访问成员函数: "<<endl;
    Vehicle *vp;
    vp=&car;
    vp->run();
    vp=&airplane;
    vp->run();
    return 0;
}


14周-初体验多态性_第1张图片

将Vehicle类的定义修改为虚函数,其余不变,当基类的指针指向派生类时,用指针调用同名虚成员函数,执行的是派生类的成员函数

#include <iostream>
using namespace std;
class Vehicle{
public:
    virtual void run() const = 0; //(3) run()为纯虚函数,const意指其为常成员函数,并非纯虚函数之必要
};
class Car: public Vehicle  //汽车
{
public:
    void run() const
    {
        cout << "run a car. "<<endl;
    }
};
class Airplane: public Vehicle  //飞机
{
public:
    void run() const
    {
        cout << "run a airplane. "<<endl;
    }
};
int main()
{
    cout<<"(a) 直接用对象访问成员函数: "<<endl;
    Car car;
    Airplane airplane;
    car.run();
    airplane.run();
    cout<<"(b)用指向基类的指针访问成员函数: "<<endl;
    Vehicle *vp;
    vp=&car;
    vp->run();
    vp=&airplane;
    vp->run();
    return 0;
}


14周-初体验多态性_第2张图片

纯虚函数只有函数名字不具备函数的功能,不能被调用!

你可能感兴趣的:(14周-初体验多态性)