从类C++外部调用指向成员方法的成员指针

Calling a member pointer to a member method from outside the class C++

本文关键字:成员 指针 成员方法 C++ 外部调用 从类      更新时间:2023-10-16

我想调用一个函数指针,指向来自该类外部的成员函数(函数指针也是同一类的成员(。

不幸的是,以下内容会产生错误:

错误:标识符"function_pointer"未定义

#include <iostream>
class test_class {
public:
void (test_class::*function_pointer)(int);
void test_function(int input) {
std::cerr << input << std::endl;
}
test_class() {
function_pointer = &test_class::test_function;
}
};
int main(void) {
test_class foo;
(foo.*function_pointer)(5);
return 0;
}

我可以在课堂上调用它,但我想避免不必要的混乱。

#include <iostream>
class test_class {
public:
void (test_class::*function_pointer)(int);
void test_function(int input) {
std::cerr << input << std::endl;
}
test_class() {
function_pointer = &test_class::test_function;
}
void call_from_within(int input) {
(this->*function_pointer)(input);
}
};
int main(void) {
test_class foo;
foo.call_from_within(5);
return 0;
}

简而言之:从类外调用function_pointer的正确语法是什么?

(foo.*foo.function_pointer)(5);

访问成员 (function_pointer( 您需要指定它们所属的实例

作为一个更复杂的例子,为什么需要这样做:

test_class foo, bar;
(foo.*bar.function_pointer)(5);

要么使用Gruffalo的解决方案,要么将该函数指针声明放在类之外

class test_class{
...
};
void (test_class::*function_pointer)(int);

除了其他答案。

由于它是c++您也可以为此使用std::function。(更多信息见此处(

#include <iostream>
#include <functional>
class test_class{
public:
std::function<void(int)> function_pointer;
void test_function(int input)
{
std::cerr << input << std::endl;
}
test_class()
{
function_pointer = std::bind(&test_class::test_function, this, std::placeholders::_1);
}
};
int main(void)
{
test_class foo;
foo.function_pointer(5);
return 0;
}

注意:您必须将std::bindthis一起使用,因为它是您的情况下的成员函数。