0

我有一个基类:

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

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

4

1 回答 1

6
int get_speed(motorcycle* m)
{
    return m->speed();
}
于 2012-07-04T12:35:50.760 回答