使用指向其他方法的指针在构造函数中分配C++方法:我做错了什么?

luc*_*one 2 c++ methods constructor pointers function

我写了以下代码:

#include <iostream>
using namespace std ;
class C{
 public:
   C::C(int) ;
   int f1(int);
   int f2(int);
   int (*f)(int);   
}

int C::f1(int x){
   return -x ;
}

int C::f2(int x){
   return x;
}

C::C(int c){
  if (c<0){
    f = f1 ;
   }
  else {
    f = f2 ;
  }
}
Run Code Online (Sandbox Code Playgroud)

这段代码不起作用,但我的想法是我希望根据传递给构造函数的值将方法f分配给f1或分配f2.

我怎样才能在C++中实现这一目标?

And*_*owl 5

如果您的成员函数是非静态的,那么您必须声明f为成员函数指针:

int (C::*f)(int);
Run Code Online (Sandbox Code Playgroud)

给定m类的成员函数的名称,通过编写C获得成员函数指针m:

&C::m
Run Code Online (Sandbox Code Playgroud)

在你的情况下:

if (c<0){
    f = &C::f1;
}
else {
    f = &C::f2;
}
Run Code Online (Sandbox Code Playgroud)

这是一个包含完整代码的实例.

通过指向成员的指针调用您的成员函数f将需要使用operator ->*.*.例如:

int main()
{
    C c(42);
    (c.*(c.f))(1729);

    int (C::*fxn)(int) = c.f;
    (c.*fxn)(0);

    C* p = &c;
    (p->*fxn)(123);
}
Run Code Online (Sandbox Code Playgroud)

或者,从给定的成员函数中fxnC:

void C::fxn()
{
    // ...      
    (this->*f)(6);
}
Run Code Online (Sandbox Code Playgroud)

在另一方面,如果你的函数f1()f()不需要上的特定实例的工作C,你可以离开的声明f的是,以及在代码中C的构造函数,但你必须标记f1(),并f2()static:

class C
{
public:
   C(int);
   static int f1(int);
// ^^^^^^
   static int f2(int);
// ^^^^^^
   int (*f)(int);
};
Run Code Online (Sandbox Code Playgroud)