类中的 C++ 注入函数
c++ inject function in class
我有这个基类:
class Task {
private:
bool enabled;
void (*foo)();
public:
virtual void init(int period) { enabled = true; }
virtual void tick() = 0;
void high(void (*f)()) { foo = f; }
void callFoo() { foo(); }
bool isEnabled() { return enabled; }
};
以及使用此方法实现Task
的类:
LedTask::LedTask(int pin, Context* pContext) {
this->pin = pin;
this->pContext = pContext;
}
void LedTask::init(int period) {
Task::init(period);
this->led = new Led(pin);
}
void LedTask::tick() {
Task::callFoo();
}
在main()
:
Task* t3 = new LedTask(LED_PIN, c);
t3->init(50);
t3->high([]{Serial.println("ok");});
这有效,但我想知道如何访问t3
实例的私人(和公共)成员; 像这样:
t3->high([]{ led->switchOn(); });
简而言之,我想在类中注入一个函数并在其中使用它的类成员。
正如我在评论中提到的,我想你的LedTask
类继承自Task
.
因此,您应该将函数指针放在 Task
类中,以支持必须在继承类中实现的纯virtual
函数:
class Task {
private:
bool enabled;
protected:
virtual void foo() = 0; // <<<<<<<<<<<<<<<<<<<<<<<<<<
public:
virtual void init(int period) { enabled = true; }
virtual void tick() = 0;
// void high(void (*f)()) { foo = f; } << not needed
void callFoo() { foo(); }
bool isEnabled() { return enabled; }
};
然后在LedTask
的第二步中,基于 std::function
构造函数参数实现foo
:
class LedTask : public Task {
public:
LedTask(uint8_t pin, Context* pContext , std::function<void()> f)
: pin_(pin), pContext_(pContext), f_(f) {
}
private:
void foo() {
f_();
}
uint8_t pin_;
Context* pContext_;
std::function<void()> f_;
};
好吧,从您的评论中听起来您需要Led
对象作为注入函数的参数。
在 init()
中创建的Led
的成员指针应传递给注入的函数。
您可以使用类似的东西
std::function<void(Led&)> f_;
或
void(*f_)(Led&);
传递该参数是在实现中完成的,如上所述:
void foo() {
f_(*led);
}
相关文章:
- 将具有固定签名的自定义函数名称注入 CRTP
- 如何在窗口中使用注入的 dll 中的参数调用函数
- 如何在不诉诸依赖注入的情况下模拟遗留函数?
- 现代编译器是否可以在使用依赖关系注入时取消虚拟化函数调用
- 使用参数调用远程进程中的函数(注入的 DLL)
- 班级名称注入和构造函数
- 检测是否已从注入的 dll 调用函数
- 类中的 C++ 注入函数
- 调用注入DLL中的函数
- C 对象组成,注入和复制构造函数
- C++ - DLL 注入和调用函数
- 从注入进程的 DLL 调用函数并更改指针函数的地址
- 依赖注入/继承设计模式的构造函数参数太多
- 为什么有些函数需要作为DLL文件注入才能工作
- 注入DLL的函数中出现访问冲突异常(5)
- C++中构造函数注入的高级配置
- 通过注入的 DLL 绕行成员函数
- 是否有可能制作一个函数包装器来运行注入的代码并返回与注入的函数相同的数据
- 使用注入的类名调用成员函数
- 在注入的 DLL 中调用函数