2010-08-25 108 views
6

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

回答

17

成员函数指针语法是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()) {} 
+0

你也可以考虑使用std :: function。 – Puppy 2010-08-25 13:21:10

+0

@DeadMG:我提到了TR1版本,但是因为具有最广泛的可用性,所以选择了Boost版本。我个人认为C++ 0x版本不够普及,新标准还没有最终确定。 – 2010-08-25 13:34:35

+0

啊,所以你做到了。由于我自己得到了一个C++ 0x编译器,我不习惯看到这些增强变体。 – Puppy 2010-08-25 14:04:29

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是,我发现所有这些信息。