c++ - 函数指针成员变量
问题描述
我在 double ( )(double) 类型的类中有一个成员变量,但是有些函数 id 喜欢存储,它们有第二个默认参数,所以它们是 double ( )(double, double) 所以我不能存储它在我当前的成员变量中。
我是否可以将我的成员变量设为 double ( )(double, double),以便它也可以存储 ( )(double)?有什么不同的方法可以完成我想要的吗?或者在使用 2 个参数 vs 1 个参数的情况下,我需要 2 个不同的变量吗?
解决方案
You need two variables. The number of arguments in the call has to match the number of arguments in the function pointer variable, so you can't use the same variable for a different number of arguments.
If you only need one of them at a time, you can save space in the structure by using a union.
double somefunc(double);
double otherfunc(double, double);
struct mystruct {
union {
double(*onearg)(double);
double(*twoarg)(double, double);
} func
// other members
};
mystruct obj;
obj.func.onearg = somefunc;
double foo = obj.func.onearg(1.2);
obj.func.twoarg = otherfunc;
double bar = obj.func.twoarg(2.5, 11.1);
推荐阅读
- javascript - 根据键为 HTMLCollection 设置值
- python - 芹菜回调不一致的参数
- php - 以编程方式“拼合”多页 PDF,就像 Acrobat 在打印之前所做的那样
- string - 如何匹配字符串?
- r - 带有星号的单杠与箱线图中的每个成对比较相对应
- javascript - 如果我有用户名和密码列表,我如何访问登录功能中的任何项目?
- flutter - 如何在颤振中创建特征验证码?
- javascript - 停止或允许关闭模态窗口
- reactjs - 使用 SWR 进行类型安全数据获取时的“any”替代方案?
- service - 如何添加新的 Android /init.rc 服务?