<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;
}
![](https://img-my.csdn.net/uploads/201205/14/1336990776_8647.JPG)
<2>
#include <iostream> using namespace std; class Vehicle { public: virtual 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; }
<3>
#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(); system("pause"); return 0; }
感言:
1)通过1和2的比较,我发现使用虚函数可以通过指向基类的的指针灵活的访问派生类中的同名成员函数。(这条的专业性是参考了一下雷同学的,我自己的表达不是很清楚)
2)纯虚基类是不可以被调用的