错误 - 无效使用不完整的类型/前向声明

Error - invalid use of incomplete type / forward declaration of

本文关键字:类型 声明 无效 用不完 错误      更新时间:2023-10-16

我知道我的问题很常见,但我一直在搜索并尝试我找到的每一个解决方案,但仍然不起作用。因此,任何帮助将不胜感激!=)

提前感谢!

我在编译时遇到此错误:

g++ -ISFML/include -Iclasses/ -W -Wall -Werror   -c -o classes/Object.o classes/Object.cpp
In file included from classes/Core.hh:18:0,
         from classes/Object.hh:4,
         from classes/Object.cpp:1:
classes/MapLink.hh:9:1: error: invalid use of incomplete type ‘struct Object’
classes/MapLink.hh:6:7: error: forward declaration of ‘struct Object’
In file included from classes/Core.hh:19:0,
         from classes/Object.hh:4,
         from classes/Object.cpp:1:
classes/Player.hh:9:1: error: invalid use of incomplete type ‘struct Object’
classes/MapLink.hh:6:7: error: forward declaration of ‘struct Object’
make: *** [classes/Object.o] Error 1

所以基本上,我有一个主要包含(主要.cpp)

#include "Core.hh"
int        main(void)
{
  ...
}

这是包含我所有包含的头文件 (Core.hh)

#ifndef __CORE_HH__
# define __CORE_HH__
#include ...
#include "Object.hh"
#include "MapLink.hh"
#include "Player.hh"
class Core
{
  ...
};
#endif /* __CORE_HH__ */

然后是给我带来麻烦的文件(对象.hh)

#ifndef __OBJECT_HH__
# define __OBJECT_HH__
#include "Core.hh"
class Object
{
  ...
};
#endif /* __OBJECT_HH__ */

(地图链接.hh)

#ifndef __MAPLINK_H__
# define __MAPLINK_H__
#include "Core.hh"
class Object;
class MapLink : public Object
{
  ...
};
#endif /* __MAPLINK_H__ */

(玩家.

#ifndef __PLAYER_H__
# define __PLAYER_H__
#include "Core.hh"
class Object;
class Player : public Object
{
  ...
};
#endif /* __PLAYER_H__ */

问题 #1:
必须仅从完全声明的类派生,否则编译器将不知道该怎么做。
删除前向声明class Object;

问题#2:
你有一个循环依赖关系:

  • 在"Core.hh"中,您可以包括"Object.hh","MapLink.hh"和"Player.hh"。
  • 在"Object.hh","MapLink.hh"和"Player.hh"中,您包括"Core.hh"。

您需要确保每个类都完全包含它继承自的类。
我不确定这些类如何相互作用,您应该在问题中提供该详细信息。
我的猜测是您需要修改您的内含物,如下所示:

  • 修改"MapLink.hh"和"PlayerLink.hh",使其包含"Object.hh",而不是"Core.hh"
  • 修改"Object.hh",使其不包含"Core.hh"。
编译器

必须知道继承类的完整接口。在这种情况下,编译器看不到您的对象。有必要在其他文件中包含object.hh文件

遵循以下内容:

  1. Object.hh - 定义__OBJECT_H__
  2. Core.hh - 定义__CORE_H__
  3. MapLink.hh - 包括Core.hh,但由于步骤 2 和#ifndef,不包括该文件的内容。
  4. Player.hh - 与步骤 3 相同。

因此,在尝试从Object继承之前,MapLink.hhPlayer.hh无法看到它的定义,并且您不能从尚未完全定义的类继承。

解决方法:具体包括要继承的类的标头。
也就是说,将#include "Object.hh"添加到MapLink.hhPlayer.hh