0

Let's say I have a Class A which inherits from QMainWindow, and a Class B. The code is like this:

In 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

In 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

And it is easy to get Class B elements in Class A, but I also want to get Class A elements in Class B(I want these two Class can access each other), the code I tried did not work. Is that the reason because Class A inherits from QMainWindow?

In order to achieve that, what can I do?
Thanks.

Theodore Tang
  • 831
  • 2
  • 21
  • 42

1 Answers1

1

Try moving B::getNumA() to the implementation file. Thus you would have something like

// 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'
}

The goal is to break the circular dependency between the headers.

Paul Floyd
  • 5,530
  • 5
  • 29
  • 43
  • I tried the way you provided, and it worked now, Thanks. But I have the following question, if I `#include 'a.h'` in `b.h` or just not include, it will get the incomplete type class error, and if I `#include 'a.h'` in `b.cpp`, the error will not show and it will work. Can you tell me why it must be included in .cpp file? – Theodore Tang Dec 08 '17 at 16:34