1

I have a question for this scheme:

class computer_mouse
{
    left_click() { };
    track_wheel() { };
    right_click() { };
}

class game_mouse: public computer_mouse
{
    double_shot() { };
    throw_grenade() { };
    sit_down() { };
}

class design_mouse: public computer_mouse
{
    increase_zoom() { };
    decrease_zoom() { };
}


class computer
{
    computer_mouse *my_mouse;
}

I want to do this:

computer_mouse *my_mouse = new game_mouse();
my_mouse->double_shot();

How can I call a descendant function from a base class?

4

3 回答 3

3

You have to use e.g. static_cast for that:

computer_mouse *my_mouse = new game_mouse();

static_cast<game_mouse*>(my_mouse)->double_shot();

From the above linked Wikipedia page:

The static_cast operator can be used for operations such as

  • Converting a pointer of a base class to a pointer of a derived class,
于 2012-09-25T17:05:19.990 回答
1

By using static_cast:

static_cast<game_mouse*>(my_mouse)->double_shot();

However, the methods should be public, and not private!

class game_mouse: public computer_mouse
{
public:
    double_shot() { };
    throw_grenade() { };
    sit_down() { };
}
于 2012-09-25T17:09:49.847 回答
0

Don't do this:

computer_mouse *my_mouse = new game_mouse();
my_mouse->double_shot();

Do this:

game_mouse *my_mouse = new game_mouse();
my_mouse->double_shot();
于 2012-09-25T17:12:21.970 回答