第十四周 程序阅读,理解虚函数与纯虚函数
2013-05-31 10:39
267 查看
/* * 程序的版权和版本声明部分 * Copyright (c)2012, 烟台大学计算机学院学生 * All rightsreserved. * 作者: 李洋 * 完成日期: 2013年 5 月 31 日 * 版本号: 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; }
当基类的指针指向派生类时,用指针调用同名成员函数,执行的是基类的成员函数,而不是派生类的成员函数。
#include <iostream> using namespace std; class Vehicle //交通工具 { public: virtual void run() const //(2) run()为纯虚函数 { 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; }
将Vehicle类的定义修改为虚函数,其余不变,当基类的指针指向派生类时,用指针调用同名虚成员函数,执行的是派生类的成员函数。
#include <iostream> using namespace std; class Vehicle //交通工具 { public: virtual void run() const =0;//(3) 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; }
将Vehicle类的定义修改为纯虚函数,找出main()函数中将使编译出错的行改为注释。
相关文章推荐
- 将第十四周的阅读程序中的Vehicle类的定义修改为纯虚函数,找出main()函数中将使编译出错的行删除
- 第十四周上机任务---程序阅读,理解函数
- 第十四周项目6-阅读程序1(对continue的理解)
- 第十四周项目6-阅读程序2(对a[i++]=的理解)
- 2013级C++第12周程序阅读项目——理解函数
- 第十四周阅读程序(3):流成员函数put,putchar输出字符
- 第十二周项目 1 阅读程序(理解函数的默认参数)
- 详解C++中的纯虚函数(虚函数区别)&多态性 以及理解
- 第十四周阅读程序——例四
- 第十四周阅读程序3
- 第十四周项目6-阅读程序(3)
- 第十四周 阅读程序1
- 第十一周项目—阅读程序,说出在测试函数中不同情况的调用产生的结果(5 d)
- 第十三周项目一 阅读程序请写出这些程序的运行结果(1 虚函数)
- 第十四周项目 阅读程序 1
- 14周阅读程序1.(3)(对纯虚函数的了解)
- 第13周 阅读程序,写出运行结果。 2.(3)交通工具类之纯虚函数
- 第十四周实践项目-阅读并运行程序,解释程序执行得到的结果(2)
- 第十四周 阅读程序(1)
- 第九周项目1:阅读并理解程序(1)