Прошу сначала ознакомиться с кодом:
Bar.h:
namespace Foo{
struct Bar {
private:
void MasterUpdate();
void SlaveUpdate();
public:
typedef void (Bar::*pUpdate)();
Bar(bool master);
pUpdate Update();
}
}
Bar.cpp
void Bar::MasterUpdate(){
// код...
}
void Bar::SlaveUpdate(){
// код...
}
void Bar::Bar() {
if(master) {
Update = &Bar::MasterUpdate;
} else {
Update = &Bar::SlaveUpdate;
}
}
main.cpp
#include <Bar.h>
Foo::Bar* bar;
int main() {
bar = new Foo::Bar(true);
while (1) {
// вызов bar->Update();
}
}
1) вызов bar->Update(); приводит к ошибке:
error: must use '.*' or '->*' to call pointer-to-member function in 'bar->Foo::Bar::Update (...)', e.g. '(... ->* bar->Foo::Bar::Update) (...)'`
2) Ошибка говорит заменить -> на ->* заменяем: bar->*Update(); - получаем ошибку:
error: 'Update' was not declared in this scope
modbusRtu->*Update()
^
3) Поискав в интернете нашёл, что вызов должен быть таким: (bar->*Update)();. Пробуем и получаем ошибку похожую на предыдущую.
error: 'Update' was not declared in this scope
(modbusRtu->*Update)()
^
Так вот, как вызвать Update у объекта bar?
#include <iostream>
#include <functional>
namespace Foo{
struct Bar {
private:
void MasterUpdate()
{
std::cout << __FUNCTION__ "\n";
}
void SlaveUpdate()
{
std::cout << __FUNCTION__ "\n";
}
public:
typedef void (Bar::*pUpdate)();
Bar(bool master)
{
if(master) {
Update = &Bar::MasterUpdate;
} else {
Update = &Bar::SlaveUpdate;
}
}
pUpdate Update;
};
}
int main() {
{
Foo::Bar bar(true);
std::invoke(bar.Update, bar);
}
{
Foo::Bar bar(false);
std::invoke(bar.Update, bar);
}
return 0;
}
Вывод:
Foo::Bar::MasterUpdate
Foo::Bar::SlaveUpdate
Продвижение своими сайтами как стратегия роста и независимости