简体   繁体   English

函数指针成员变量

[英]function pointer member variable

I have a member variable in a class of type double ( )(double) but there are some functions id like to store that have a 2nd default parameter so they're double ( )(double, double) so I can't store it in my current member variable.我在 double ( )(double)类型的类中有一个成员变量,但是有一些函数 id 喜欢存储它们具有第二个默认参数,因此它们是 double ( )(double, double) 所以我无法存储它在我当前的成员变量中。

Is it possible for me to make my member variable a double ( )(double, double) so it could also store a ( )(double)?我可以将我的成员变量设为 double ( )(double, double) 以便它还可以存储 ( )(double) 吗? Is there any different approach that could accomplish what I want?有什么不同的方法可以完成我想要的吗? Or would I need 2 different variables for the case where its using 2 parameters vs 1?或者在使用 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM