C ++:指向不同函数的成员函数指针数组

时间:2010-08-25 12:36:28

标签: c++ pointers function

我有一个包含成员函数foo()和bar()的类A,它们都返回一个指向类B的指针。如何在类A中声明一个包含函数foo和bar作为成员变量的数组?我如何通过数组调用函数?

2 个答案:

答案 0 :(得分:18)

成员函数指针语法为ReturnType (Class::*)(ParameterTypes...),例如:

typedef B* (A::*MemFuncPtr)(); // readability
MemFuncPtr mfs[] = { &A::foo, &A::bar }; // declaring and initializing the array
B* bptr1 = (pointerToA->*mfs[0])(); // call A::foo() through pointer to A
B* bptr2 = (instanceOfA.*mfs[0])(); // call A::foo() through instance of A

参见例如this InformIT article了解有关成员指针的详细信息。

您可能还想查看Boost.BindBoost.Function(或它们的TR1等价物),它们允许您将成员函数指针不透明地绑定到实例:

typedef boost::function<B* ()> BoundMemFunc;
A instanceOfA;
BoundMemFunc mfs[] = { 
    boost::bind(&A::foo, &instanceOfA), 
    boost::bind(&A::bar, &instanceOfA) 
};
B* bptr = mfs[0](); // call A::foo() on instanceOfA

要将此类数组用作成员,请注意您无法使用成员初始值设定项列表初始化数组。因此,您可以在构造函数体中指定它:

A::A {
    mfs[0] = &A::foo;
}

...或者您使用的类型实际上可以在std::vectorboost::array进行初始化:

struct A {
    const std::vector<MemFuncPtr> mfs;
    // ...
};

namespace {
    std::vector<MemFuncPtr> init_mfs() {
        std::vector<MemFuncPtr> mfs;
        mfs.push_back(&A::foo);
        mfs.push_back(&A::bar);
        return mfs;
    }
}

A::A() : mfs(init_mfs()) {}

答案 1 :(得分:2)

您正在寻找的是成员函数指针。这是一个简短的样本,显示了它们的声明和用法:

#include <iostream>

class B {
public:
  B(int foo): foo_(foo) {
    std::cout << "Making a B with foo_ = " << foo_ << std::endl;
  }
  ~B(void) {
    std::cout << "Deleting a B with foo_ = " << foo_ << std::endl;
  }
  int foo_;
};

class A {
public:
  A(void) {
    funcs_[0] = &A::foo;
    funcs_[1] = &A::bar;
  }

  B* foo(void) {
    return new B(3);
  }

  B* bar(void) {
    return new B(5);
  }

  // Typedef for the member function pointer, for everyone's sanity.
  typedef B* (A::*BMemFun)(void);
  BMemFun funcs_[2];
};

int main(int argc, char *argv[]) {
  A a;
  for (int i = 0; i < 2; ++i) {
    A::BMemFun func = a.funcs_[i];
    // Call through the member function pointer (the .* operator).
    B* b = (a.*func)();
    delete b;
  }
  return 0;
}

C++ FAQ section on pointers to member functions是我找到所有这些信息的地方。