调用派生类方法

时间:2012-07-04 12:34:37

标签: c++ c++11 polymorphism

我有一个基类:

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?
}

现在,返回速度的最佳方法是什么?

1 个答案:

答案 0 :(得分:6)

int get_speed(motorcycle* m)
{
    return m->speed();
}