在结构外部调用指向函数的指针
Call a pointer-to-function outside the structure
我有一个结构,里面有一个指向同一结构的函数的指针。现在我需要调用一个指针来在结构外部函数。我给出了以下代码的示例:
#include <iostream>
struct test {
void (test::*tp)(); // I need to call this pointer-to-function
void t() {
std::cout << "testn";
}
void init() {
tp = &test::t;
}
void print() {
(this->*tp)();
}
};
void (test::*tp)();
int main() {
test t;
t.init();
t.print();
(t.*tp)(); // segfault, I need to call it
return 0;
}
(t.*tp)();
正在尝试调用在全局命名空间定义为void (test::*tp)();
的成员函数指针tp
,请注意,它实际上被初始化为空指针(通过零初始化1(,调用它会导致UB,一切皆有可能。
如果要在对象t
上调用t
的数据成员tp
(即t.tp
(,则应将其更改为
(t.*(t.tp))();
^
|
---- object on which the member function pointed by tp is called
如果确实要调用全局tp
,则应对其进行适当的初始化,例如
void (test::*tp)() = &test::t;
然后你可以
(t.*tp)(); // invoke global tp on the object t
1关于零初始化
在以下情况下执行零初始化:
1( 对于每个具有静态或线程本地存储持续时间的命名变量
that is not subject to constant initialization (since C++14)
,在任何其他初始化之前。
@songyuanyao的答案是有效的。但是,您确定要以这种方式使用您的结构吗?为什么不只使用继承和虚拟方法?:
class base_test {
public:
virtual void t() { std::cout << "testn"; }
void print() { t(); }
};
然后你可以对它进行子类化:
class my_test : base_test {
public:
virtual void t() { std::cout << "my testn"; }
};
在main()
函数(或任何地方(中,可以让函数返回对基类的指针或引用,这些指针或引用实际上是子类的实例。这样,您就不必担心指针。
缺点是你必须在编译时了解不同的测试(然后甚至在使用现场,正如我刚才解释的那样(。如果你这样做,我会使用常见的成语。
相关文章:
- QMetaObject invokeMethod的基于函数指针的语法
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- c++r值引用应用于函数指针
- 模板函数指针和lambda
- 是否可以将llvm::FunctionType转换为C/C++原始函数指针
- 带有类的函数指针
- () 函子后面的括号,而不是函数指针?
- 全局作用域中函数指针的赋值
- 使用"Task"函数指针队列定义作业管理器
- 将成员函数指针作为参数传递给模板方法
- 如何创建对象函数指针C++映射?
- 匹配函数指针作为模板参数?
- 通过函数指针定义类范围之外的方法
- 存储在类中的函数指针
- C++从函数指针数组调用函数
- 将返回值存储在函数指针数组的指针中是如何工作的?
- 整数键映射到头文件中的成员函数指针
- 从类成员函数到类 C 函数指针的转换
- 如何将内联匿名函数分配给C++函数指针
- 将字符缓冲区强制转换为函数指针