2011-12-12 30 views
-1

要存儲一個類的函數在一個數組中,下面的鏈接http://sourcemaking.com/design_patterns/state/cpp/1包含如下代碼(機器是類名)。一個類的函數陣列

void(Machine:: *ptrs[])() = 
    { 
    Machine::off, Machine::on 
    }; 

在該鏈路的示例不與克++編譯器投擲錯誤編譯如下

$ g++ state.cpp 
state.cpp: In function ‘int main()’: 
state.cpp:89:18: error: invalid use of non-static member function ‘void Machine::off()’ 
state.cpp:89:32: error: invalid use of non-static member function ‘void Machine::on()’ 
state.cpp:97:15: error: expected unqualified-id before ‘*’ token 

我使用克++版本4.5.2

$ g++ --version 
g++ (Ubuntu/Linaro 4.5.2-8ubuntu4) 4.5.2 
Copyright (C) 2010 Free Software Foundation, Inc. 
This is free software; see the source for copying conditions. There is NO 
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 

能的陣列來限定像這樣,我無法找到像這樣的數組定義。如果這個例子是正確的,爲什麼不編譯。

+0

您試圖在數組中放置的成員函數是靜態的嗎?如果不是,你如何期望他們能夠工作,因爲他們將缺少* this *參考。 – OSH

+0

閱讀關於指向成員函數的指針。 –

+0

...成員函數指針不是單獨調用 - 你只需要用類的成員調用它們即可。函數指針獨立於類成員的地址。 – Nate

回答

2

如果您定義了typedef for your member functions,您將極大地簡化代碼。

class Machine 
{ 
public: 
    void on(){} 
    void off(){} 
}; 


int main() 
{ 

    typedef void (Machine::*MachineFunctionPtr)(); 

    MachineFunctionPtr temp[] = { &Machine::off , &Machine::on }; 


    //To invoke a function use this syntax 
    Machine mymachine; 
    ((mymachine).*(temp[1]))(); 

的雖這麼說你的錯誤是由於在函數名前失蹤「&」。

如果你不想use typedef the correct way is something like

void(Machine:: *ptrs[])() = 
{ 
    &Machine::off, &Machine::on 
}; 
Machine fsm; 
int num; 
while (1) 
{ 
    cout << "Enter 0/1: "; 
    cin >> num; 
    ((fsm).*(ptrs[num]))(); 
} 
+0

如何讀取數組MachineFunctionPtr(MachineFunction Ptr是一個ptr到..) –

+0

我試着添加&哪個在調用對象Machine的函數時使用代碼Machine fsm;(fsm。* ptrs [0])( );錯誤是$ g ++ state.cpp state.cpp:在函數'int main()'中: state.cpp:97:15:錯誤:預期'*'標記之前的非限定標識。有關完整的代碼,請查看以下鏈接http:// sourcemaking。com/design_patterns/state/cpp/1 –

+0

@Talespin_Kit請參閱我的更新回答 –

2

爲了能夠到你的成員函數指針添加到您的陣列,您需要預先考慮它們的標識符與地址的運營商&

實施例:

struct Obj { 
    void func_1() {} 
    void func_2() {} 
}; 

int 
main (int argc, char *argv[]) 
{ 
    void (Obj::* pointers[])() = { 
    &Obj::func_1, &Obj::func_2 
    }; 
} 
+0

@Talespin_Kit'(object。* pointers [0])();' –

1

這是多個C++的方式來做到這一點:

#include <vector> 
#include <iostream> 

struct A { 
    typedef void (A::*memfpt)(); 

    A() : arr({ &A::foo, &A::bar }) 
    {} 

    void foo() 
    { 
    std::cout<<"foo"<<std::endl; 
    } 
    void bar() 
    { 
    std::cout<<"bar"<<std::endl; 
    } 

    std::vector<memfpt> arr; 
}; 

int main() { 
    A a; 

    for (auto &it : a.arr) 
    { 
     (a.*it)(); 
    } 
} 

代替原始陣列中,我使用的std ::矢量,並且代替的是無法形容憎惡,我使用the typedef

您的具體示例不編譯,因爲:

  1. 線97:(fsm. *ptrs[num])();應該是(fsm.*ptrs[num])(); - 你需要刪除的空間,因爲調用一個成員函數指針應使用.*->*
  2. 完成
  3. 第89行:Machine::off, Machine::on應該是&Machine::off, &Machine::on,因爲那是您如何獲得指向成員函數的指針。
+0

請你考慮解釋爲什麼代碼在這裏http:///sourcemaking.com/design_patterns/state/cpp/1不編譯 –

+1

@Talespin_Kit編輯問題以解決您的編譯錯誤。請注意,編譯器仍然吐出關於未使用變量的警告。 –