[英]Static member array of pointers to member functions
我正在嘗試在.cpp文件中定義一個屬性,該屬性應該是指向名為Hand的類的成員函數的指針的數組。
數組和函數都是Hand的成員,並且數組是靜態的(如果不需要,請更正我)。
這是我達到的目標:
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”聲明為函數數組。
我想類型定義很破舊,所以我需要知道如何正確定義
語法很復雜:
class Hand
{
bool has_sflush();
static bool (Hand::*hfunctions[])();
...
};
bool (Hand::*Hand::hfunctions[])() = {&Hand::has_sflush, ...};
一種解決方法是逐漸增加復雜性,使用cdecl.org在每一步進行檢查:
int (*hFunctions)()
將hFunctions聲明為返回int的函數的指針
int (Hand::*hFunctions)()
將hFunctions聲明為指向int類的Hand函數的成員的指針
警告:C語言不支持-“指向類成員的指針”
int (Hand::*hFunctions[])()
將hFunctions聲明為指向返回int的Hand函數類成員的指針的數組
警告:C語言不支持-“指向類成員的指針”
現在用bool
替換int
(不幸的是,cdecl.org不理解bool
); 這樣就得到了聲明的語法。
對於定義,用Hand :: hFunctions替換hFunctions
,然后像您一樣添加初始化部分。
數組和函數都是Hand的成員,並且數組是靜態的(如果不需要,請更正我)。
如果我正確理解您的要求, 則不應該 。 您應該將操作抽象為一個基類,對其進行專門化處理,並將該數組作為指向該基類的指針的數組保存:
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;
};
如果您有不帶參數的非靜態成員函數並返回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]();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.