使类中的函数指针依赖于初始化值
Posted
技术标签:
【中文标题】使类中的函数指针依赖于初始化值【英文标题】:make function pointer in class dependent on initialized value 【发布时间】:2021-08-30 13:06:39 【问题描述】:我想创建一个对象,并在初始化期间选择一个函数来执行一些计算。对于N
阶的多项式,必须调用某个函数,定义为someFunN
。现在我可以用函数指针来做到这一点。我通过构造函数中的一个巨大的 if 块来做到这一点,
if (order == 2)
SolveFun = &someFunPoly2;
else if (order == 3)
SolveFun = &someFunPoly3;
// etc...
else
SolveFun = &someFunPoly50;
但由于我的功能要到约 50 个订单,所以写起来有点乏味。还有其他方法可以定义someFunN
并在Polynomial
的初始化期间分配此函数吗?
someFunN
的内容是由Matlab中的代码生成脚本生成的,还是可以修改的。
#include <iostream>
using namespace std;
struct vec;
class Polynomial;
double someFunPoly2(Polynomial *Poly, vec Pt, vec Ur);
double someFunPoly3(Polynomial *Poly, vec Pt, vec Ur);
double someFunPoly10(Polynomial *Poly, vec Pt, vec Ur);
struct vec
double x, y;
vec(double x_, double y_) : x(x_), y(y_)
;
class Polynomial
public:
int order, n;
double *p;
double (*SolveFun)(Polynomial *, vec, vec);
Polynomial(int order_)
order = order_;
n = order + 1;
p = new double[n];
for (int i = 0; i < n; i++)
p[i] = 0.0;
if (order == 2)
SolveFun = &someFunPoly2;
else if (order == 3)
SolveFun = &someFunPoly3;
else
SolveFun = &someFunPoly10;
// more and more cases...
;
double someFunPoly2(Polynomial *Poly, vec Pt, vec Ur)
// some calculations for a poly of order 2
cout << "using Poly with order " << Poly->order << " and this is someFunPoly2" << endl;
return 2;
double someFunPoly3(Polynomial *Poly, vec Pt, vec Ur)
// some calculations for a poly of order 2
cout << "using Poly with order " << Poly->order << " and this is someFunPoly3" << endl;
return 3;
double someFunPoly10(Polynomial *Poly, vec Pt, vec Ur)
// some calculations for a poly of order 10
cout << "using Poly with order " << Poly->order << " and this is someFunPoly10" << endl;
return 10;
int main()
vec P = vec(1.0, 2.0);
vec U = vec(0.3, 0.5);
Polynomial *Poly2 = new Polynomial(2);
Polynomial *Poly10 = new Polynomial(10);
cout << Poly2->SolveFun(Poly2, P, U) << endl;
cout << Poly10->SolveFun(Poly10, P, U) << endl;
return 0;
【问题讨论】:
指向函数的指针数组? @S.M.哦,太棒了,这是个好主意! 【参考方案1】:您可能正在寻找查找表:
#include <iostream>
void say_hello() std::cout << "Hello!\n";
void say_bye() std::cout << "Bye!\n";
void say_thanks() std::cout << "Thanks!\n";
int main(void)
int n = /*something 0-2*/;
void (*says[])() = say_hello, say_bye, say_thanks;
void (*speech)() = says[n];
speech();
如果 n
是 0、1 或 2,那么它将分别打印 Hello!
、Bye!
或 Thanks!
。
【讨论】:
以上是关于使类中的函数指针依赖于初始化值的主要内容,如果未能解决你的问题,请参考以下文章
InternetCrackUrlW 不填充结构化类中指针后面的字符串值