使用函数指针数组调用类的方法

问题描述

我想用 C++ 编写一个包含函数指针数组的程序。 代码如下:

   #include <iostream>
   using namespace std;

   class MyClass {
   int a,b;
   public:
   MyClass(int i,int j) : a(i),b(j) {}
   int add() { return a + b; }
   int sub() { return a - b; }
 };

void func(int (MyClass::* funcPtr[])(),MyClass& a,int i) {
  if (i == 0) {
    funcPtr[i] = &MyClass::add;
    funcPtr;
  }

  if (i == 1) {
    funcPtr[i] = &MyClass::sub;
    funcPtr;
}
cout << " Result: " << (a.*funcPtr[i])() << endl;
}

int main(){
  int auswahl = 0;
  int i = 4,j = 5;

  cout << "Which function? [0]-Add [1]-Substract\n";
  cin >> select;
  
  MyClass a(i,j);
  func(NULL,a,select);
}

在玩了很多之后,我成功地编译了程序。但它在运行时抛出“写访问冲突”。

问题似乎与:

funcPtr[i] = &MyClass::add;
funcPtr[i] = &MyClass::sub;

如果你能帮我解决问题就太好了。

非常感谢,祝您玩得愉快!

解决方法

当您在函数中传递 NULLnullptr 时,这一行:

funcPtr[i] = &MyClass::add;

正在将索引 i 写入空数组!

你必须为你的函数提供一个数组来写入:

 MyClass a(i,j);
 int (MyClass::* funcPtr[2])();
 func(funcPtr,a,select);

请注意,使用 std::array 而不是 c 样式数组可以避免此问题,因为它们不可为空:

void func(std::array<int (MyClass::*)(),2> funcPtr,MyClass& a,int i) {
    // ...
}

// ...

std::array<int (MyClass::*)(),2> funcPtr;
func(funcPtr /* cannot pass null */,i);