gpt4 book ai didi

c++ - 在结构外调用指向函数的指针

转载 作者:太空狗 更新时间:2023-10-29 20:08:33 24 4
gpt4 key购买 nike

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

#include <iostream>

struct test {
void (test::*tp)(); // I need to call this pointer-to-function
void t() {
std::cout << "test\n";
}
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)();正在尝试调用成员函数指针 tp在全局命名空间中定义为 void (test::*tp)(); ,请注意它实际上被初始化为空指针(通过 zero initialization 1),调用它会导致 UB ,一切皆有可能。

如果要调用数据成员tpt (即 t.tp )在对象上 t ,你应该把它改成

(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关于零初始化

Zero initialization is performed in the following situations:

1) For every named variable with static or thread-local storage duration that is not subject to constant initialization (since C++14), before any other initialization.

关于c++ - 在结构外调用指向函数的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52802698/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com