关于成员函数指针动态数组的语法问题



我已经搜索了很多,但无法找出正确的语法。我所尝试的结果是一些语法错误。没有成员函数,我可以让它编译。

这是我的例子:

class TestClass
{
public:
typedef bool (TestClass::* demoFunc)(int);
struct Container
{
Container(demoFunc func)
: func(func)
{}
demoFunc func;
};
Container* containers;
bool foo1(int dummy) { return true; }
bool foo2(int dummy) { return true; }
void InvokeFunction(int i)
{
TestClass::Container container = containers[i];
// How do I call the function here?
bool result = container.func(0); // here is the error
}
};
int main()
{
TestClass testClass;
testClass.containers = new TestClass::Container[]
{
TestClass::Container(&TestClass::foo1),
TestClass::Container(&TestClass::foo2),
};
testClass.InvokeFunction(0);
testClass.InvokeFunction(1);
}

这是编译器错误:

表达式前面的圆括号必须具有(pointer-to-)函数类型

操作符->*允许使用指向实例的指针调用成员函数。操作符.*允许您直接使用实例或对实例的引用来调用成员函数。

为了调用该函数,可以在它们后面加上成员函数地址。

struct Test
{
bool foo(int val){ return true; }
};
int main()
{
Test test_instance;
Test* test_pointer = &test_instance;
Test& test_reference = test_instance;

auto FuncAddress = &Test::foo;

//calling foo using pointer
(test_pointer->*FuncAddress)(0);

//calling foo using directly the instance
(test_instance.*FuncAddress)(0);

//calling foo using a reference to the instance
(test_reference.*FuncAddress)(0);

return 0;
}

解引用/调用成员指针需要一个目标对象(在本例中为TestClass类型)。

假设您想使用this:bool result = (this->*container.func)(0);

Pointers_to_members语法不是微不足道的,在您的情况下,它将是:

bool result = (this->*(container.func))(0);

作为替代,std::invoke(C + + 17)可以使用

std::invoke(container.func, this, 0);