Kii*_*ity 7 c++ pointers function
我有一个包含成员函数foo()和bar()的类A,它们都返回一个指向类B的指针.如何在类A中声明一个包含函数foo和bar作为成员变量的数组?我如何通过数组调用函数?
Geo*_*che 19
成员函数指针语法是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
Run Code Online (Sandbox Code Playgroud)
有关指向成员的指针的更多详细信息,请参阅此InformIT文章.
您可能还想查看Boost.Bind和Boost.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
Run Code Online (Sandbox Code Playgroud)
要将此类数组用作成员,请注意您无法使用成员初始值设定项列表初始化数组.因此,您可以在构造函数体中为其分配:
A::A {
mfs[0] = &A::foo;
}
Run Code Online (Sandbox Code Playgroud)
...或者您使用的类型实际上可以在那里初始化,std::vector或者boost::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()) {}
Run Code Online (Sandbox Code Playgroud)