我试图在.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:error:将'hfunctions'声明为函数数组。
我想类型定义很好,所以我需要知道如何才能正确定义
答案 0 :(得分:2)
语法是一个相当复杂的语法:
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声明为指向Hand函数返回int
的成员的指针警告:C中不支持 - “指向成员的指针”
int (Hand::*hFunctions[])()
将hFunctions声明为指向Hand函数返回int
的成员的指针数组警告:C中不支持 - “指向成员的指针”
现在用int
替换bool
(遗憾的是,cdecl.org不理解bool
);所以你得到了声明的语法。
对于定义,用Hand :: hFunctions替换hFunctions
,并像你一样添加初始化部分。
答案 1 :(得分:2)
数组和函数都是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;
};
答案 2 :(得分: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]();