/* (程序头部注释开始)
* 程序的版权和版本声明部分
* Copyright (c) 2011, 烟台大学计算机学院学生
* All rights reserved.* 文件名称:虚基类
* 作 者: 郭岩岩
* 完成日期:2012 年5月 14日
* 版 本 号: vc.1
* 对任务及求解方法的描述部分
* 输入描述:
* 问题描述:
* 程序输出:
*程序头部的注释结束
*/
#include <iostream>
using namespace std;
class Vehicle
{
public:
virtual void run() const =0;
};
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 car.
run a airplane.
(b) 用指向基类的指针访问成员函数:
run a car.
run a airplane.
请按任意键继续. . .
总结:把基类中的函数改为虚函数后在主函数中定义指向基类对象的指针后,把派生类对象的地址赋值给指针变量时,该指针就指向派生类对象,即完成了基类可以访问派生类。
把基类改为抽象类后不能再给抽象类声明对象,纯虚函数也不能被调用。