【问题标题】:Incomplete type C++不完全类型 C++
【发布时间】:2012-04-25 19:26:39
【问题描述】:

当我尝试执行此代码段时出现以下错误:“菜单未命名类型”。我知道它与循环引用有关,但对于我的一生,我无法弄清楚是什么.此外,menu、go 和 manager 都在反复报错。代码段贴在下面:

#ifndef GO__H
#define GO__H

#include <SDL.h>
#include <iostream>
#include <string>
using std::cout; using std::endl; 
using std::string;

#include "ioManager.h"
#include "gui.h"
#include "clock.h"
#include "menu.h"

//class Menu;
class Go {
public:
    Go ();
    void play();
private:
    SDL_Surface *screen;
    Gui gui;
    Menu menu;

    void drawBackground() const;
    Go(const Go&);
    Go& operator=(const Go&);
};

#endif

这里是菜单:

#ifndef MENU_H
#define MENU_H

#include <SDL.h>
#include <iostream>

#include "ioManager.h" 
#include "gui.h"
#include "clock.h"
#include "manager.h"

class Menu {
public:
    Menu ();
    void play();

private:
    const Clock& clock;
    bool env;

    SDL_Surface *screen;
    Gui gui;
    Manager mng;

    void drawBackground() const;
    Menu(const Menu&);
    Menu& operator=(const Menu&);
};

#endif

经理:

#ifndef MANAG_H
#define MANAG_H

#include "go.h"
class Manager { 
  Go go;
  //other code
}

你能看出问题出在哪里吗?错误信息:

在 go.h:13:0 包含的文件中, 来自 manager.h:33, 来自 manager.cpp:2: menu.h:28:11:错误:字段“mng”的类型不完整

【问题讨论】:

  • menu.h 会以某种方式引用 go.h 吗?这可能会导致这种错误。
  • 尝试将代码减少到产生错误的最少行数 - 即删除除 Menu 之外的所有成员以及所有相关的所有不需要的内容,然后编辑问题。跨度>
  • 尝试在class GO 中将Menu menu; 更改为Menu* menu;
  • 另外,您的编译器使用 Menu 报告错误的文件的行号。那会很有帮助
  • 请包含完整编译器消息,行号和文件名。如果行号超过几十行,还可以考虑在代码列表中包含行号。从提示和片段中重构这些信息并不有趣。

标签: c++ circular-reference


【解决方案1】:

manager.h 包括go.h,其中包括menu.h,其中包括manager.h ...

class Menu 在到达class Manager 的定义之前就被定义了。

然而,class Menu 需要一个 Manager,但由于编译器不知道 Manager,但它不知道它有多大。

您可以转发声明class Manager 并使Menumng 成员成为指针或引用:

class Manager;

class Menu {
    ...
    Manager* mng;

    // or this:
    //Manager& mng; 
    ...

Here's a good explanation of circular references and how to fix them.

【讨论】:

  • 我是否可以通过从 go.h 中删除 #include menu.h 来摆脱它? - 但是这些类中的每一个都需要包含类中的一个对象。
【解决方案2】:

看来您在 manger.h 中的 Manager 类声明末尾缺少分号。

您还缺少 #endif 来关闭您的包含防护。

【讨论】:

  • 哦,是的,没发现,这也是个问题。
  • 假设这是完整的源文件。
  • 不,这些在真实文件中。
猜你喜欢
  • 2016-10-06
  • 2012-11-18
  • 1970-01-01
  • 2013-09-15
  • 1970-01-01
  • 1970-01-01
  • 2016-12-07
  • 2017-01-08
  • 1970-01-01
相关资源
最近更新 更多