【发布时间】:2018-01-20 09:02:28
【问题描述】:
我不知道如何调用存储在类成员 std::array 中的函数指针。
namespace logic {
class Chance {
std::array<void(logic::Chance::*)(), 15> m_redChances;
};
}
void logic::Chance::redChance1 {
std::cout << "Red chance one\n";
}
logic::Chance::Chance()
{
m_redChances[0] = &Chance::redChance1;
}
到目前为止看起来还不错,但是当我想在另一个成员函数中调用此函数时,似乎没有任何效果。只有第一行编译,但它不调用我的函数。其余的给出错误:
logic::Chance::anotherMemberFunction() {
m_redChances[0];
(*m_redChances[0]*)();
(*logic::Chance::m_redChances[0])();
m_redChances[0]();
*m_redChances[0]();
*logic::Chance::m_redChances[0]();
*logic::Chance::m_redChances[0];
*(*m_redChances[0])();
}
“*”的操作数必须是指针类型
和
apprent call 的括号前的表达式必须有 (pointer-to-) 函数类型
编辑#
所以我尝试使用std::function 并且不得不稍微改变类设计,我想实现这样的目标
struct Foo {
std::array<std::function<void(Foo&)>, 3> funArray;
Foo() {
funArray[0] = &Foo::fun1;
funArray[1] = &Foo::fun2;
}
void fun1() {
std::cout << "fun1\n";
}
void fun2() {
std::cout << "fun2\n";
}
std::function<void(Foo&)> getFunction(int i) {
return funArray[i];
}
};
int main() {
Foo foo;
foo.getFunction(0);
std::cin.get();
}
您可以猜到,这并没有调用我的函数,我再次尝试了每种组合以正确返回它,但无法弄清楚,这是唯一可以编译的,但什么也不做。如何返回另一个函数在std::array 中的函数调用?有点乱,但希望你明白我的意思。
【问题讨论】:
-
类定义中没有声明的成员函数,以后不能定义。这可能是您错误的来源之一。此外,函数定义至少需要一个空的形式参数列表,
()。
标签: c++ arrays std function-pointers