如何在C ++中将函数数组公开为类成员?

时间:2012-01-03 01:38:20

标签: c++

我必须在我的应用程序中公开一系列函数。这些函数实际上是该类的方法,我将在构造函数中填充数组。例如:

void Cpu::print() { // some func
    std:cout << "hi";
}

void Cpu::Cpu() { // class ctor
  funcArray = { &Cpu::print }
}

然后我想这样做:

Cpu myCpu;
(myCpu.*funcArray[0])();

我的所有功能都将遵循相同的签名“void()”。

这可能吗?

1 个答案:

答案 0 :(得分:0)

您无法分配数组,但可以使用初始化列表:

class Cpu {
public:
    typedef void (Cpu::*Func)();

    ...

    Func funcArray[CONSTANT];
};

Cpu::Cpu() : funcArray({ &Cpu::print }) {
    // the rest of the array is filled with NULL pointers
}

然后

Cpu cpu;

(cpu.*(cpu.funcArray[0]))();
相关问题