我有一个基类:
class motorcycle
{
public:
virtual int speed()
{ return 0; }
}
还有一些继承基类的类(在示例中只有2个,但我可以有很多类):
class honda: public motorcycle
{
public:
int speed()
{ return 2; }
}
class yamaha: public motorcycle
{
public:
int speed()
{ return 1; }
}
我有一个指向基类的指针,指向派生类之一:
honda* h = new honda();
...
int speed = get_speed(h);
get_speed
的位置:
int get_speed(motorcycle* m)
{
// How to return speed according to m class?
}
现在,返回速度的最佳方法是什么?
答案 0 :(得分:6)
int get_speed(motorcycle* m)
{
return m->speed();
}