C ++:成员函数指针的数组,指向不同的函数 [英] C++: Array of member function pointers to different functions

查看:145
本文介绍了C ++:成员函数指针的数组,指向不同的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a class A which contains member functions foo() and bar() which both return a pointer to class B. How can I declare an array containing the functions foo and bar as a member variable in class A? And how do I call the functions through the array?

推荐答案

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

The member function pointer syntax is ReturnType (Class::*)(ParameterTypes...), so e.g.:

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

的实例调用A :: foo()。 此InformIT文章获取关于成员指针的更多细节。

See e.g. this InformIT article for more details on pointers to members.

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

You might also want to look into Boost.Bind and Boost.Function (or their TR1 equivalents) which allow you to opaquely bind the member-function-pointers to an instance:

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

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

To use such an array as a member, note that you can't initialize arrays using the member initializer list. Thus you can either assign to it in the constructor body:

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

......或者您使用的类型实际上可以初始化为 std :: vector boost :: array

... or you use a type that can actually be initialized there like std::vector or 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()) {}

这篇关于C ++:成员函数指针的数组,指向不同的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆