简体   繁体   English

C++:指向成员 function 的指针

[英]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();我需要一个关于我的 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?我怎样才能从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. .*的右侧不是在左侧的上下文中解析的,而是在当前的 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是你的 object,它的成员的名字是Q.movePtr ,“解引用成员指针”运算符是.* ,所以你需要

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

Pointers-to-members seem very neat until you notice that they easily make your code completely unreadable.指向成员的指针看起来非常简洁,直到您注意到它们很容易使您的代码完全不可读。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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