使 class 中的函数指针依赖于初始化值

make function pointer in class dependent on initialized value

我想创建一个对象,并在初始化期间选择一个函数来执行一些计算。对于 N 阶多项式,必须调用一些函数,定义为 someFunN。现在我可以用一个函数指针来做到这一点。我通过构造函数中的一个巨大的 if 块来做到这一点,

if (order == 2)
    SolveFun = &someFunPoly2;
else if (order == 3)
    SolveFun = &someFunPoly3;
// etc...
else
    SolveFun = &someFunPoly50;

但是因为我有直到 order ~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;
}

您可能正在查找 table:

#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!