c++ - 调用和初始化类的静态成员函数
问题描述
我有以下代码:
#include <stdint.h>
#include <inttypes.h>
#include <stdio.h>
class A {
public:
int f();
int (A::*x)();
};
int A::f() {
return 1;
}
int main() {
A a;
a.x = &A::f;
printf("%d\n",(a.*(a.x))());
}
我可以在哪里正确初始化函数指针。但我想将函数指针设为静态,我想在这个类的所有对象中维护它的单个副本。当我将其声明为静态时
class A {
public:
int f();
static int (A::*x)();
};
我不确定将其初始化为函数 f 的方式/语法。任何资源都会有所帮助
解决方案
A static pointer-to-member-function (I guess you already know this is different from a pointer to a static member function) is a kind of static member data, so you have to provide a definition outside the class like you would do with other static member data.
class A
{
public:
int f();
static int (A::*x)();
};
// readable version
using ptr_to_A_memfn = int (A::*)(void);
ptr_to_A_memfn A::x = &A::f;
// single-line version
int (A::* A::x)(void) = &A::f;
int main()
{
A a;
printf("%d\n",(a.*(A::x))());
}
推荐阅读
- css - 即使大小固定,页脚也会缩小+奇怪的行为
- unity3d - 没有在 TextMeshPro 组件上更新玩家分数
- ios - Swift 5/iOS 13 - 嵌入在导航控制器中的奇怪视图位置行为
- mongodb - 无法使用 Spark 结构化流向 MongoDB 发送数据
- flutter - type '(String) => dynamic' 不是 'Widget' 类型的子类型
- ionic5 - 不重复的 Ionic5 FavoriteService
- python - 将字典的值对转换为元组
- c++ - 停止 clang-format 在 VS Code 中将元素拆分为多行
- python - 如何从外部应用程序驱动 keras-rl 训练?
- static - 如何防止hyper-v虚拟交换机的ip地址被更改?