【问题标题】:c++ "Incomplete type not allowed" error accessing class reference information (Circular dependency with forward declaration)访问类引用信息的c++“不允许不完整类型”错误(带有前向声明的循环依赖)
【发布时间】:2014-03-11 16:27:23
【问题描述】:

最近在我的代码中出现了一些关于我现在所知道的循环依赖的问题。简而言之,有两个类,Player 和 Ball,它们都需要使用来自对方的信息。在代码中的某个点,两者都将传递对另一个的引用(来自另一个包含两个 .h 文件的类)。

阅读完之后,我从每个文件中删除了#include.h 文件,并进行了前向声明。这解决了能够在彼此中声明类的问题,但是当我尝试访问传递的对对象的引用时,我现在留下了“不完整的类型错误”。周围似乎有一些类似的例子,但经常与更复杂的代码混合在一起,很难缩小到基础。

我已经以最简单的形式(本质上是一个骨架)重写了代码。

球.h:

class Player;

class Ball {
public:
    Player& PlayerB;
    float ballPosX = 800;
private:

};

播放器.h:

class Ball;

class Player {
public:
    void doSomething(Ball& ball);
private:
};

播放器.cpp:

#include "Player.h"

void Player::doSomething(Ball& ball) {
    ball.ballPosX += 10;                   // incomplete type error occurs here.
}

任何帮助理解为什么会这样将不胜感激:)

【问题讨论】:

  • #include "Ball.h" in Player.cpp

标签: c++ class reference forward-declaration


【解决方案1】:

在我的情况下,这是因为一个错字。

我有类似的东西

struct SomethingStrcut { /* stuff */ };

typedef struct SomethingStruct smth;

请注意结构的名称与类型定义的名称不同。

我将struct 拼错为strcut。

查看您的代码,看看您是否有一些拼写错误。

【讨论】:

    【解决方案2】:

    这是我所拥有的以及导致我的“不完整类型错误”的原因:

    #include "X.h" // another already declared class
    class Big {...} // full declaration of class A
    
    class Small : Big {
        Small() {}
        Small(X); // line 6
    }
    //.... all other stuff
    

    我在“Big.cpp”文件中做了什么,我在其中声明了以 X 作为参数的 A2 的构造函数是..

    大.cpp

    Small::Big(X my_x) { // line 9 <--- LOOK at this !
    }
    

    我写的是“Small::Big”而不是“Small::Small”,真是个愚蠢的错误.. 我一直收到 X 类的错误“现在允许不完整的类型”(在第 6 行和第 9 行),这完全造成了混乱..

    无论如何,这就是可能发生错误的地方,主要原因是我写它的时候很累,我需要 2 个小时的探索和重写代码来揭示它。

    【讨论】:

      【解决方案3】:

      Player.cpp 需要 Ball 类的定义。所以只需添加#include "Ball.h"

      Player.cpp:

      #include "Player.h"
      #include "Ball.h"
      
      void Player::doSomething(Ball& ball) {
          ball.ballPosX += 10;                   // incomplete type error occurs here.
      }
      

      【讨论】:

        【解决方案4】:

        如果您按此顺序放置定义,则将编译代码

        class Ball;
        
        class Player {
        public:
            void doSomething(Ball& ball);
        private:
        };
        
        class Ball {
        public:
            Player& PlayerB;
            float ballPosX = 800;
        private:
        
        };
        
        void Player::doSomething(Ball& ball) {
            ball.ballPosX += 10;                   // incomplete type error occurs here.
        }
        
        int main()
        {
        }
        

        函数doSomething的定义需要类Ball的完整定义,因为它访问其数据成员。

        在您的代码示例模块中,Player.cpp 无法访问 Ball 类的定义,因此编译器会发出错误。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-04-24
          • 2011-12-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多