如何从包装在类中的成员访问包装器类的成员

How to access members of wrapper class from member which is wrapped in class

本文关键字:成员 包装 访问      更新时间:2023-10-16

例如,我得到了:"包装机.h"

class wrapper : public QWidget
{
    Q_OBJECT
    public:
    Wrapped_class m_class;
    private:
    QTimer* m_timer;
}

"Wrapped_class.h"

class Wrapped_class
{
public:
Wrapped_class();
public slots:
f(); // slot which is called when m_timer send signal timeout()
}

"Wrapped_class.cpp"

Wrapped_class::Wrapped_class()
{
QOBject::connect(wrapper::m_timer, SIGNAL(timeout()), this, SLOT( f()))
}

我收到错误,包装器::m_timer无法访问

您需要对类进行pointerreference才能访问其non static成员。在包装时将pointer传递给包装的类

将这样的东西添加到您的Wrapped_class

void Wrapped_class::setWrapper(wrapper *w)
{
    m_wrapper = w;
}

并在包装对象时调用此函数。在构造函数中初始化m_rappernullptr

根据您的意图和系统设计,您可以选择:

    将"包装"类
  1. 的指针或引用传递给"包装"类。 请注意,您必须将包装类定义为friend才能访问private成员。
  2. 编写"wrapper"类的成员函数来处理两个类之间的交互。(这并不真正符合您的限制,但它是一种设计替代方案。
m_timer不是

静态成员,因此您无法像那样访问它。在Wrapped_class.cpp中,您需要包装类的实例才能使用它

除了wrapper::m_timer不是静态的问题外,它也是私有的,这意味着Wrapped_class无法访问它。您需要Wrapped_class成为wrapper的朋友,以便它访问私人成员。