实验1.1目的:
阅读程序,写出执行结果并上机检验。
实验代码:
#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(); system("pause"); return 0; }
运行结果:
(a) 直接用对象访问成员函数: run a vehicle. run a car. run a airplane. (b) 用指向基类的指针访问成员函数: run a vehicle. run a vehicle. Press any key to continue
实验1.2目的:
将Vehicle类的定义修改为虚函数,其余不变,请写出程序的执行结果,并在上机时对照理解
实验代码:
#include <iostream> using namespace std; class Vehicle { public: virtual void run() const {cout << "run a vehicle. " << endl;} }; class Car:public Vehicle { public: virtual void run() const {cout << "run a car. " << endl;} }; class Airplane:public Vehicle { public: virtual 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(); system("pause"); return 0; }
运行结果:
(a) 直接用对象访问成员函数: run a vehicle. run a car. run a airplane. (b) 用指向基类的指针访问成员函数: run a car. run a airplane. Press any key to continue
实验1.3目的:
如果将Vehicle类的定义修改为纯虚函数,找出main()函数中将使编译出错的行删除(或改为注释),请写出程序的执行结果,并在上机时对照理解
实验代码:
#include <iostream> using namespace std; class Vehicle { public: virtual void run() const = 0; }; class Car:public Vehicle { public: virtual void run() const {cout << "run a car. " << endl;} }; class Airplane:public Vehicle { public: virtual 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(); system("pause"); return 0; }
实验结果:
(a) 直接用对象访问成员函数: run a car. run a airplane. (b) 用指向基类的指针访问成员函数: run a car. run a airplane. Press any key to continue
实验心得:
从实验1.1到实验1.2最后到实验1.3,老师真的是良苦用心啊,从实验1.1指向基类的指针无法访问到派生类的数据一步一步让我们体会虚函数的作用:虚函数的作用是允许在派生类中重新定义与基类同名的函数,并且可以通过基类的指针或引用来访问基类和派生类中的同名函数,最后到纯虚函数,为派生类保留一个函数的名字,以便派生类根据需要对它进行定义。