C++问题,谢谢大虾.
定义一个车(vehicle)基类,有Run、Stop等成员函数,由此派生出自行车(bicycle)类、汽车(motorcar)类,从bicycle和motorcar派生出摩托车(motorcycle)类,它们都有Run、Stop等成员函数。观察虚函数的作用。
参考答案:class vehicle
{
public:
void Run(){cout<<"Run in vehicle\n";}
virtual void Stop(){cout<<"Stop in vehicle\n";}
};
class bicycle : public vehicle
{
public:
void Run(){cout<<"Run in bicycle\n";}
virtual void Stop(){cout<<"Stop in bicycle\n";}
};
class motorcar : public vehicle
{
public:
virtual void Stop(){cout<<"Stop in motorcar\n";}
};
class motorcycle : pulic vehicle, public motocar
{
public:
virtual void Stop(){count<<"Stop in motorcycle\n";}
};
void main()
{
vehicle v, *v;
bicycle b;
motorcar m;
motorcycle mb;
v.Run();
b.Run();
//m.Run();
//mb.Run();
v.Stop();
b.Stop();
m.Stop();
mb.Stop();//不论虚函数与否,类对象总是访问自己的函数
//而我们希望的是用基类的指针访问子类的函数,那样我们只需要一个指
//针就可以访问当前不同子类的同一个函数了.这在实际当中很有用.
v = &b;
v->Stop();
v = &m;
v->Stop();
v = &mb;
v->Stop();
}
水平有限,给你讲不太清楚,可以好好看看书,书上讲的好.