【目的】
1. 進一步多態性的基本概念
2. 學會利用虛函數實現多態性
3. 學會在設計中利用純虛函數構造抽象基類
【任務1】閱讀下面的程序
(任務1.1)請寫出程序的執行結果,並在上機時對照理解
#include <iostream>
using namespace std;
class Vehicle
{
public:
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();
system("pause");
return 0;
}
(任務1.2)如果將Vehicle類的定義修改爲虛函數,其餘不變,請寫出程序的執行結果,並在上機時對照理解
class Vehicle
{public:
virtual void run() const { cout << "run a vehicle. "<<endl; } //(2) run()爲虛函數
};
(任務1.3)如果將Vehicle類的定義修改爲純虛函數,找出main()函數中將使編譯出錯的行刪除(或改爲註釋),請寫出程序的執行結果,並在上機時對照理解
class Vehicle
{public:
virtual void run() const = 0; //(3) run()爲純虛函數
};
(任務1.4)提交博文,記錄實驗過程和結果,用自己的話概括你對虛函數、多態性和抽象類的理解。
#include <iostream>
using namespace std;
class Vehicle
{
public:
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();
system("pause");
return 0;
}
去掉Vehicle v;
v.run();
積累經驗:
(1)基類不能訪問派生類中的信息。因此其輸出結果應爲 基類的部分。抽象類的作用是作爲一個類族的共同基類。
(2)當改爲虛函數,其就可實現動態的多態性。通過指向基類的指針訪問派生類中同名的成員函數,實現不同功能。
(3)抽象類不能實例化,即不能建立對象。還有純虛函數是不能被調用的。所以要刪除那兩行