2013-07-23 91 views
2


我想在一個.cpp定義文件,它應該是一個指針數組到一個名爲手工類的成員函數的屬性。
這兩個陣列和功能都是手工的成員,該陣列是靜態的(請糾正我,如果它不應該)。
這是我達到什麼:靜態成員數組成員函數

static bool Hand::*(Hand::hfunctions)[]()= 
{&Hand::has_sflush,&Hand::has_poker,&Hand::has_full,&Hand::has_flush, 
&Hand::has_straight,&Hand::has_trio,&Hand::has_2pair,&Hand::has_pair};            


我得到這個錯誤:hand.cpp:96:42:錯誤:「hfunctions」作爲函數數組的聲明。
我猜類型定義撥錯,所以我需要知道我怎樣才能使定義權

+0

問題是什麼? – hivert

+2

你究竟想在這裏實現什麼? –

回答

2

語法是一個相當令人費解之一:

class Hand 
{ 
    bool has_sflush(); 
    static bool (Hand::*hfunctions[])(); 
    ... 
}; 

bool (Hand::*Hand::hfunctions[])() = {&Hand::has_sflush, ...}; 

一種方式來獲得這個是逐漸增加的複雜性,使用cdecl.org在每一步檢查自己:

int (*hFunctions)() 

declare hFunctions as pointer to function returning int


int (Hand::*hFunctions)() 

declare hFunctions as pointer to member of class Hand function returning int

Warning: Unsupported in C -- 'pointer to member of class'


int (Hand::*hFunctions[])() 

declare hFunctions as array of pointer to member of class Hand function returning int

Warning: Unsupported in C -- 'pointer to member of class'


現在更換intbool(可悲的是,cdecl.org不明白bool);所以你得到了聲明的語法。

對於定義,取代手工:: hFunctions hFunctions,並添加初始化部分,像你這樣。

+0

cdecl.org,我不知道那個工具,謝謝!如果工作了C++甚至會更好 – user1754322

+0

等待,這似乎支持大多數的C++還... – user1754322

1

如果你不帶任何參數非靜態成員函數,返回bool你應該寫類似

typedef bool (Hand::*hfunction_non_static)(); 
hfunction_non_static f_non_static [] = 
{ 
    &Hand::has_sflush, 
    &Hand::has_poker, 
    ....... 
}; 
Hand h; 
(h.*f_non_static[0])(); 

如果你有靜態功能,你應該寫類似

typedef bool (*hfunction_static)(); 
hfunction_static f_static [] = {&Hand::has_sflush, ....}; 
f_static[0](); 
+0

謝謝!這不正是我一直在問,因爲我有麻煩的時候,我不得不告訴編譯器「hfunctions是手的成員」在.cpp文件中。無論如何,我從你的回答中學到了很多東西,例如typedef的使用使得這更容易。 – user1754322

2

Both the array and the functions are members of Hand and the array is static(please correct me if it should not).

如果我明白你問什麼正確,你不應該。您應該將操作抽象爲基類,將其專門化,並將該陣列作爲指向基類的指針數組:

struct Match // need a better name 
{ 
    virtual bool matches() = 0; 
    virtual ~Match() = default; 
}; 

struct MatchSFlush: public Match { ... }; 

class Hand 
{ 
    static std::vector<std::unique_ptr<Match>> matches; 
}; 
+0

「你不應該」 - 我想這意味着「你不應該以你所做的方式來實現」;問題是「數組應該是靜態的嗎?」。無論如何+1。 – anatolyg

+0

是的,這是關於不這樣實施的。通常當你需要創建一個抽象行爲的函數數組時,這意味着「走向虛擬」。 – utnapistim

+0

爲了理解這個答案,我將不得不進行研究。感謝您的努力。 – user1754322