错误:无效使用不完整类型'struct Item'

时间:2014-03-31 21:47:54

标签: c++

我的标题遇到了很多麻烦,并确保所有内容都正确声明。首先关闭我的文件:

//Main.cpp
#include "Item.h"
#include "Warehouse.h"
using namespace std;

int main() {
    ...
}

//Item.h
#ifndef ITEM_H
#define ITEM_H
#include <string>
using namespace std;

class Item {
    ...
};
#endif  /* ITEM_H */

//Item.cpp
#include "Item.h"

//Warehouse.h
#define WAREHOUSE_H
#ifndef ITEM_H
#define ITEM_H
using namespace std;

class Item;
class Warehouse {
    ...
private:
    Item* array; //problem starts with this
};
#endif  /* WAREHOUSE_H */

//Warehouse.cpp
#include "Warehouse.h"
#include "Item.h"

Warehouse::Warehouse() {
    array = new Item[arraySize]; //and this is where I get the error
}

我很确定问题与我在Warehouse.h中的标题有关,但我尝试的每个组合都不起作用。很抱歉,如果没有足够的代码发布,但我认为问题在于包含和声明。

提前谢谢。

编辑:澄清这不在一个文件中。我只是这样写它来简化事情。以上每个都是一个单独的文件。

2 个答案:

答案 0 :(得分:3)

标题文件Warehouse.h中的包含警示不正确。

而不是

//Warehouse.h
#define WAREHOUSE_H
#ifndef ITEM_H
#define ITEM_H
using namespace std;

// ...

#endif  /* WAREHOUSE_H */

你想要

//Warehouse.h
#ifndef WAREHOUSE_H
#define WAREHOUSE_H
using namespace std;

// ...

#endif  /* WAREHOUSE_H */

对于当前版本,item.h中的类定义永远不会包含在Warehouse.cpp中,因为混合包含Warehouse.h中的警卫会阻止item.h因为

的顺序
//Warehouse.cpp
#include "Warehouse.h"
#include "Item.h"    //Warehouse.cpp
#include "Warehouse.h"
#include "Item.h"

然后编译器在那时不知道Item的定义,因此错误。

另一件事:不要在头文件中形成using namespace std的习惯。这会在某些时候引发问题。

答案 1 :(得分:0)

问题不在此声明中

private:
    Item* array; //problem starts with this

您可以定义指向不完整类型的指针。

我认为问题出现在一个语句中,你尝试使用operator new为这个指针分配一个对象,或者取消引用指针。

此外,我没有看到任何理由您不希望在标题Warehouse.h中包含标题Item.h而不是使用详细的名称

class Item;