码迷,mamicode.com
首页 > 其他好文 > 详细

第十三周 阅读程序 4 运用虚函数的前后对比问题讲解(1)

时间:2015-05-27 13:58:48      阅读:108      评论:0      收藏:0      [点我收藏+]

标签:

/*
*Copyright (c)2014,烟台大学计算机与控制工程学院
*All rights reserved.
*文件名称:d.cpp
*作    者:张旺华
*完成日期:2015年5月27日
*版 本 号:v1.0
*/

#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;
}

运行结果:

技术分享

知识点应用及心得:

直接用对象访问成员函数,采用静态关系直接调用本身成员函数,

指向基类的指针访问成员函数:,由于基类中run()不是虚函数,

Vehicle *vp
说明,vp是指向基类的,在调用是必定调用基类成员函数

    

第十三周 阅读程序 4 运用虚函数的前后对比问题讲解(1)

标签:

原文地址:http://blog.csdn.net/wh201458501106/article/details/46045165

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!