第十四周阅读程序2

来源:互联网 发布:农产品网络销售方案 编辑:程序博客网 时间:2024/05/18 03:49
/** 程序的版权和版本声明部分:* Copyright (c) 2013, 烟台大学计算机学院* All rights reserved.* 文件名称:test.cpp* 作    者:任子仪* 完成日期:2014年 5月 27日* 版 本 号:v12.1* 输入描述:无* 问题描述:。* 程序输出:* 问题分析:略* 算法设计:略*/#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;}


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

示例图片:

心得体会:好懒啊,真的不想写着心得体会

0 0
原创粉丝点击