首页 > 解决方案 > 函数指针成员变量

问题描述

我在 double ( )(double) 类型的类中有一个成员变量,但是有些函数 id 喜欢存储,它们有第二个默认参数,所以它们是 double ( )(double, double) 所以我不能存储它在我当前的成员变量中。

我是否可以将我的成员变量设为 double ( )(double, double),以便它也可以存储 ( )(double)?有什么不同的方法可以完成我想要的吗?或者在使用 2 个参数 vs 1 个参数的情况下,我需要 2 个不同的变量吗?

标签: c++pointersfunction-pointers

解决方案


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);

推荐阅读