簡體   English   中英

我怎樣才能制作一個方法指針數組?

[英]How can I make an array of method pointers?

我想創建一個指向方法的指針數組,這樣我就可以快速 select 調用一個基於 integer 的方法。但是我在語法上遇到了一些困難。

我現在擁有的是:

class Foo {
     private:
        void method1();
        void method2();
        void method3();

        void(Foo::*display_functions[3])() = {
            Foo::method1,
            Foo::method2,
            Foo::method3
        };
};

但我收到以下錯誤消息:

[bf@localhost method]$ make test
g++     test.cpp   -o test
test.cpp:11:9: error: cannot convert ‘Foo::method1’ from type ‘void (Foo::)()’ to type ‘void (Foo::*)()’
   11 |         };
      |         ^
test.cpp:11:9: error: cannot convert ‘Foo::method2’ from type ‘void (Foo::)()’ to type ‘void (Foo::*)()’
test.cpp:11:9: error: cannot convert ‘Foo::method3’ from type ‘void (Foo::)()’ to type ‘void (Foo::*)()’
make: *** [<builtin>: test] Error 1

是的,你可以,你只需要獲取他們的地址:

        void(Foo::*display_functions[3])() = {
            &Foo::method1,
            &Foo::method2,
            &Foo::method3
        };

...但是,如果您有接口的virtual方法或為多方法模式調用所有方法的簡單方法,可能會更好。

您可以使用typedef作為指向您的方法的指針類型,然后將您的方法存儲在包含該類型的std::array中:

class Foo {
private:
    void method1() {};
    void method2() {};
    void method3() {};

    typedef void (Foo::* FooMemFn)();

    std::array<FooMemFn,3> display_functions = {
        &Foo::method1,
        &Foo::method2,
        &Foo::method3
    };
};

除了typedef ,您還可以使用using語句:

using FooMemFn = void (Foo::*)();

請注意,您必須將operator&與 class 方法一起使用以獲得指向方法的指針。

旁注:如果display_functions static 不會在各種 class 實例之間發生變化,請考慮制作它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM