2013-07-23 167 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