C++: Call function of Class B when a function of Class A is called (Pointer to Class A is a Member of Class B)

C++: Call function of Class B when a function of Class A is called (Pointer to Class A is a Member of Class B)

class A {
  void functionA();
};

class B {
  A* A_;
  void functionB();
};

如果在 class B 实例之外调用 functionA(),我如何在 class B 实例中自动调用 functionB()? (指向 Class A 实例的指针是 class B 实例的成员)。 我正在寻找类似 Qt 中的 SIGNAL/SLOT 方法的东西。

一种选择是在 A 实例中使用 function object as a callback. In the following example, B's constructor registers a lambda function,只要调用函数 A,A 就会调用该实例。反过来,这个 lambda 只是简单地调用函数 B。

#include <functional>
#include <iostream>

class A {
public:
    void functionA() {
        std::cout << "Function A called" << std::endl;
        if (callback_) {
            callback_();
        }
    }

    void setCallback(std::function<void(void)> callback) {
        this->callback_ = callback;
    }

private:
    std::function<void(void)> callback_;
};

class B {
public:
    B(A* a) : A_(a) {
        A_->setCallback([this](){this->functionB();});
    }

    void functionB() {
        std::cout << "Function B called" << std::endl;
    }

private:
    A* A_;
};

int main() {
    A a;
    B b = B(&a);

    a.functionA();
}

输出:

Function A called
Function B called

正如您在输出中看到的,当在 main 中调用 a.functionA() 时,函数 B 也被自动调用。