如何将成员函数作为参数传递并在派生对象上执行方法列表
How to pass a member function as a parameter and execute list of methods on derived object
我想创建一个将整数值映射到成员函数的数组,以便
(this->*actionMap[i])();
执行该方法。 为了填充数组,我想要一个将数组元素设置为相应操作的方法。
我在之前的问题中看到它应该使用 std::function 和 std::bind 但我没有遵循语法,而且我不明白如何声明数组: 如何正确地将成员函数作为参数传递
这是M(非(我们 请注意,我希望基类能够在派生对象上执行方法。
#include <iostream>
using namespace std;
class Base;
typedef void (Base::*Action)();
class Base {
Action actions[3];
public:
void setAction(int a, Action act) {
actions[a] = act;
}
void f() { cout << "f"; }
void go() {
for (int i = 0; i < 3; i++)
(this->*actions[i])();
}
};
struct Derived : public Base {
void g() { cout << "g"; }
void h() { cout << "h"; }
Derived() {
setAction(1, f);
setAction(2, g);
setAction(1, h);
}
};
int main() {
Derived d;
d.go();
}
在
派生对象上执行方法。
因此,在执行方法时,必须具有派生对象的句柄。其中两种方法不在Base::
,因为它们不在Base
内部。它们在Derived
内部,所以指针可能是Derived::*
的,但这毫无意义,并且会破坏我猜你想要的模型。我想你可以让你的方法g
h
,f
Base
内部的虚拟。但这又会破坏目的,我猜是一种类似观察者的模式。
你想做的,基本上很容易通过适当的抽象来解决 -std::function
和std::bind
。
#include <iostream>
#include <array>
#include <functional>
class Base {
std::array<std::function<void()>, 3> actions;
public:
void setAction(int a, std::function<void()> act) {
actions.at(a) = act;
}
void f() { std::cout << "f"; }
void go() {
for (auto&& action : actions) {
if (action) {
action();
}
}
}
};
struct Derived : public Base {
void g() { std::cout << "g"; }
void h() { std::cout << "h"; }
Derived() {
setAction(1, std::bind(&Derived::f, this));
setAction(2, std::bind(&Derived::g, this));
setAction(1, std::bind(&Derived::h, this));
}
};
int main() {
Derived d;
d.go();
}
相关文章:
- 如何使用单独文件中的派生类访问友元函数对象
- 使用基类指针创建对象时,缺少派生类析构函数
- 为什么此派生对象无法访问基类的后递减方法?
- 将带有派生模板的对象传递给接受具有基本模板的对象的功能
- 放置派生C++的新基子对象
- 在 C++ 中将对象转换为派生类型
- 链表包含 c++ 中不同的派生类对象
- 如何在不使用指针的情况下将派生类的对象作为参数传递给基类中的函数?
- 如何在新的派生对象中获取基本对象的数据?
- 如何将成员函数作为参数传递并在派生对象上执行方法列表
- 获取我的基类以递增派生类对象整数
- 派生类中的对象
- 在没有默认构造函数的情况下创建的派生对象
- OOP 标识派生对象
- 如何创建派生对象的向量?
- 按基类对象访问派生类资源时出错
- 将基类分配给派生对象,反之亦然,以C++以及静态和动态对象之间的差异
- static_cast将此对象派生到C++中的基类
- 如何在构造函数完成后立即销毁从 QWindow 对象派生的内容
- 我可以判断std::type_info对象是否等于另一个对象或从另一个对象派生的类吗?