且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

“字段具有不完全类型”错误

更新时间:2023-11-10 10:51:16

您正在使用 MainWindowClass 类型的向前声明。这很好,但它也意味着你只能声明一个指针或引用的类型。否则编译器不知道如何分配父对象,因为它不知道前向声明类型的大小(或者如果它实际上有一个无参数的构造函数等)。

You are using a forward declaration for the type MainWindowClass. That's fine, but it also means that you can only declare a pointer or reference to that type. Otherwise the compiler has no idea how to allocate the parent object as it doesn't know the size of the forward declared type (or if it actually has a parameterless constructor, etc.)

所以,你要么:

// forward declaration, details unknown
class A;

class B {
  A *a;  // pointer to A, ok
};

或者,如果不能使用指针或引用....

Or, if you can't use a pointer or reference....

// declaration of A
#include "A.h"

class B {
  A a;  // ok, declaration of A is known
};

有时,编译器需要知道 A

At some point, the compiler needs to know the details of A.

如果您只存储指向 A 的指针,那么当您声明 B 。它需要它们在某些时候(当你实际上将指针解引用 A )时,这可能在实现文件中,您将需要包含包含 A 的声明。

If you are only storing a pointer to A then it doesn't need those details when you declare B. It needs them at some point (whenever you actually dereference the pointer to A), which will likely be in the implementation file, where you will need to include the header which contains the declaration of the class A.

// B.h
// header file

// forward declaration, details unknown
class A;

class B {
public: 
    void foo();
private:
  A *a;  // pointer to A, ok
};

// B.cpp
// implementation file

#include "B.h"
#include "A.h"  // declaration of A

B::foo() {
    // here we need to know the declaration of A
    a->whatever();
}