从类C++外部调用指向成员方法的成员指针
Calling a member pointer to a member method from outside the class C++
我想调用一个函数指针,指向来自该类外部的成员函数(函数指针也是同一类的成员(。
不幸的是,以下内容会产生错误:
错误:标识符"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::bind
与this
一起使用,因为它是您的情况下的成员函数。
相关文章:
- 从成员指针到整个结构/类的强制转换
- OOP 中的单成员指针
- 使用结构成员指针在C++中填充结构
- 聚合初始化,将成员指针设置为同一结构成员
- 空指针常量 (nullptr)、空指针值和空成员指针值之间有什么区别?
- 共享 C++ 的数据成员指针
- 如何声明指向成员内容的成员指针m_pmd/m_pmf并访问它们?
- 从类C++外部调用指向成员方法的成员指针
- 结构成员指针是否自动初始化为零?
- 如何删除类内类类型的类成员指针
- 是否打印指向已定义 int 的成员指针
- 指向常量的成员指针
- 通过此指针访问时的成员差异和自身的成员指针(简单的 QT 示例问题)
- 类数据成员指针的非类型模板参数包无法使用 gcc 编译
- 为什么我不能在同一行中定义两个相同类型的类的成员指针
- 将类成员指针传递给 Lambda 捕获列表 c++11
- 在单一实例类中将成员指针设置为 null 的正确方法是什么
- 无法删除在destructor中的成员指针的课程
- 删除对象而不调用成员指针的析构函数
- 当派生类的基类具有成员指针时,对其进行深层复制