要存儲一個類的函數在一個數組中,下面的鏈接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.
能的陣列來限定像這樣,我無法找到像這樣的數組定義。如果這個例子是正確的,爲什麼不編譯。
您試圖在數組中放置的成員函數是靜態的嗎?如果不是,你如何期望他們能夠工作,因爲他們將缺少* this *參考。 – OSH
閱讀關於指向成員函數的指針。 –
...成員函數指針不是單獨調用 - 你只需要用類的成員調用它們即可。函數指針獨立於類成員的地址。 – Nate