【发布时间】:2015-06-18 05:38:37
【问题描述】:
我在初始化一个以函数指针作为成员的结构数组时遇到了麻烦。
class Record
{
private:
typedef void (*display_fn_t) ();
struct record {
int a;
display_fn_t disp;
};
static const record rec[];
void disp1() { cout << "Display 1 with a string to display" << endl; }
void disp2() { cout << "Display 2 with an integer to display" << endl; }
public:
int find() { /* logic to find the record comes here */ }
void display() {
for (int i = 0; i < 2; i++) {
rec[i].disp();
}
}
}
const Record::record Record::rec[] = {
{ 10, disp1 },
{ 11, disp2 }
};
int main()
{
Record r;
if (r.find())
r.display();
return 0;
}
当我编译上面的代码时,我得到以下编译错误:
mca_record.cpp:56:错误:类型为“void (Record::)()”的参数确实 不匹配‘void (*)()’
【问题讨论】:
-
指向成员函数的指针不与指向非成员函数的指针相同。 SO上必须有数百甚至数千个重复项。问题是指向成员函数的指针需要调用实际的对象实例,而指向非成员函数的指针则不需要。
-
另外,您可能想了解
std::function和std::bind。 -
另外,缺少分号。
标签: c++ arrays function-pointers