[cpp]
#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:
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;
}