首先,要明确运行时刻的多态依赖于类的继承与虚函数。
(可以去看我之前写的文章)
基本做法是:在基类与派生类中定义函数原型相同的两个虚函数,然后定义基类的指针,用积累的指针指向不同的派生类对象,通过虚函数即可实现运行时多态。
代码例子:
#include <iostream>
using namespace std;
class vehicle {
public:
vehicle(int n = 0, int m = 0) { //初始基类的构造函数
axspeed = n;//对数据成员进行赋值
Weigh = m;
}
virtual void run() { //初始基类的两个成员函数
cout << "vehicle run!" << endl;
}
void stop() {
cout << "vehicle stop!" << endl;
}
private:
int axspeed;
int Weigh;
};
class bicycle : virtual public vehicle {
public:
bicycle(int x = 0, int y = 0, int z = 0) : vehicle(x, y) //中间派生类的构造函数,
//需要为初始基类提供形参
{
Height = z;
}
void run() {
cout << "bicycle run!" << endl;
}
void stop() {
}
private:
int Height;
};
class motorcar : virtual public vehicle {
public:
motorcar(int x = 0, int y = 0, int z = 0) : vehicle(x, y) //中间派生类的构造函数,
//需要为初始基类提供形参
{
SeatNun = z;
}
void run() {
cout << "motorcar run!" << endl;
}
void stop() {
}
private:
int SeatNun;
};
class motorbicycle : public bicycle, public motorcar {
public:
void run() {
cout << "motorbicycle run!" << endl;
}
void stop() {
}
};
int main() {
vehicle v;
bicycle b;
motorcar mot;
motorbicycle mo;
v.run();
b.run();
mot.run();
mo.run();
vehicle *ve = new vehicle;
ve = &v;
ve->run();
ve = &b;
ve->run();
ve = &mot;
ve->run();
ve = &mo;
ve->run();
return 0;
}
希望对大家有帮助!!!