QT两个类互相访问

Qt two classes access each other

本文关键字:访问 两个 QT      更新时间:2023-10-16

假设我有一个从 QMainWindow继承的 Class A和一个 Class B。代码是这样:

a.h中:

#ifndef A_H
#define A_H
#include <QMainWindow>
#include "b.h"
class A : public QMainWindow
{
    Q_OBJECT
public:
    A(QWidget *parent = 0);
    ~A();
    B TestingB;
    int tryingNumA = 0;
    void getNumB() {
        qDebug() << TestingB.tryingNumB; //worked
    }
};
#endif // A_H

b.h中:

#ifndef B_H
#define B_H
#include <QDebug>
class A;
class B
{
public:
    B();
    int tryingNumB = 1;
    A *testingA;
    void getNumA() {
        qDebug() << testingA->tryingNumA; //did not work, error: invalid use of incomplete type 'class A'
    }
};
#endif // B_H

,很容易在Class A中获得Class B元素,但是我也想在Class B中获得Class A元素(我希望这两个Class可以互相访问),我尝试过的代码无效。这是因为Class AQMainWindow继承吗?

为了实现这一目标,我该怎么办?
谢谢。

尝试将B::getNumA()移至实现文件。因此,您会有

之类的东西
// b.cpp
#include "b.h"
#include "a.h"
 void b::getNumA() {
    qDebug() << testingA->tryingNumA; //did not work, error: invalid use of incomplete type 'class A'
}

目的是打破标题之间的圆形依赖性。