简体   繁体   中英

C++ : pointer on member function


namespace Borg
{
 class BorgQueen
 {
 public:
   BorgQueen();
   bool move(Borg::Ship *ship, Destination dest) {return ship->move(dest);}
   void fire(Borg::Ship *ship, Federation::Starfleet::Ship *target) {ship->fire(target);}
   void destroy(Borg::Ship *ship, Federation::Ship *target) {ship->fire(target);}
 
   void (Borg::BorgQueen::*firePtr)(Borg::Ship *ship, Federation::Starfleet::Ship *target) = &Borg::BorgQueen::fire;
   void (Borg::BorgQueen::*destroyPtr)(Borg::Ship *ship, Federation::Ship *target) = &Borg::BorgQueen::destroy;
   bool (Borg::BorgQueen::*movePtr)(Borg::Ship *ship, Destination dest) = &Borg::BorgQueen::move;
 };
};

I need to have a pointers on mebers of my class: movePtr -> move(); This is what I have mannage to comme whit but i access it (the pointer); how can i call it from the ptr?

int main()
{
   Borg::BorgQueen Q();
   [...]
   // this does work 
   Q.movePtr(...);
   Q.*movePtr(...);
   *(Q.movePtr)(...)


}

The right-hand side of .* is not resolved in the context of the left-hand side, but in the current scope.

Like this:

int main()
{
    bool (Borg::BorgQueen::*go)(Borg::Ship *ship, Destination dest) = &Borg::BorgQueen::move;
    Borg::BorgQueen queen;
    //...
    (queen.*go)(something something...);
}

Q is your object, the name of its member is Q.movePtr , the "dereference pointer-to-member" operator is .* , so you need

(Q.*Q.movePtr)(...);

Pointers-to-members seem very neat until you notice that they easily make your code completely unreadable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM