在结构外部调用指向函数的指针

Call a pointer-to-function outside the structure

本文关键字:函数 指针 结构 外部调用      更新时间:2023-10-16

我有一个结构,里面有一个指向同一结构的函数的指针。现在我需要调用一个指针来在结构外部函数。我给出了以下代码的示例:

#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()函数(或任何地方(中,可以让函数返回对基类的指针或引用,这些指针或引用实际上是子类的实例。这样,您就不必担心指针。

缺点是你必须在编译时了解不同的测试(然后甚至在使用现场,正如我刚才解释的那样(。如果你这样做,我会使用常见的成语。