我尝试寻找解决方案,但找不到。
所以我有一个头文件items.h
:
#ifndef ITEMS_H
#define ITEMS_H
#include <vector>
using std::vector;
int create_item();
class itemClass
{
public:
short int xTile;
short int yTile;
bool playerHas;
short int category;
short int weaponCategory;
}extern vector<itemClass> items;
#endif
然后我在items.cpp
哪里尝试使用这个向量create_item()
:
#include "stdafx.h"
#include "SDL.h"
#include "items.h"
#include <vector>
using namespace std;
vector<itemClass> items;
int index = 0;
int create_item()
{
//select category for the created item
short int itemCategory = rand() % 3;
switch(itemCategory)
{
case WEAPON:
//increase weapons list by one
items.resize(items.size() + 1);
index = items.size();
//set appropriate item category
items.at(index).category = itemCategory;
items.at(index).weaponCategory = rand() % 9;
break;
}
我遗漏了一些不重要的部分。无论如何,只要我不在标头中将向量声明为 extern,此代码就可以正常工作,而只是将其保留在本地。当我尝试这样做时,为什么会导致错误?
编辑:对不起,我忘了包括错误:
1>c:\users\aske\documents\c++\roguelike\roguelike\items.cpp(12):错误 C2371:'items':重新定义;不同的基本类型
1>
c:\users\aske\documents\c++\roguelike\roguelike\items.h(53) :参见“项目”的声明1>c:\users\aske\documents\c++\roguelike\roguelike\items.cpp(36): error C2228: left of '.resize' must have class/struct/union
1> 类型是'int'
1>c:\users\aske\documents\c++\roguelike\roguelike\items.cpp(36): error C2228: left of '.size' must have class/struct/union
1> 类型是'int'
1>c:\users\aske\documents\c++\roguelike\roguelike\items.cpp(38): error C2228: left of '.size' must have class/struct/union
1> 类型是'int'
1>c:\users\aske\documents\c++\roguelike\roguelike\items.cpp(41): error C2228: left of '.at' must have class/struct/union
1> 类型是'int'
1>c:\users\aske\documents\c++\roguelike\roguelike\items.cpp(41): error C2228: left of '.category' must have class/struct/union
1>c:\users\aske\documents\c++\roguelike\roguelike\items.cpp(43): error C2228: left of '.at' must have class/struct/union
1> 类型是'int'
1>c:\users\aske\documents\c++\roguelike\roguelike\items.cpp(43): error C2228: left of '.weaponCategory' must have class/struct/union
1>c:\users\aske\documents\c++\roguelike\roguelike\items.cpp(46): error C2228: left of '.at' must have class/struct/union
1> 类型是'int'
1>c:\users\aske\documents\c++\roguelike\roguelike\items.cpp(46): error C2228: left of '.weaponCategory' must have class/struct/union
1>c:\users\aske\documents\c++\roguelike\roguelike\items.cpp(47): error C2228: left of '.at' must have class/struct/union
1> 类型是'int'
1>c:\users\aske\documents\c++\roguelike\roguelike\items.cpp(47): error C2228: left of '.weaponCategory' must have class/struct/union
1>c:\users\aske\documents\c++\roguelike\roguelike\items.cpp(48): 错误 C2228: '.at' 的左边必须有类/结构/联合
1> 类型是'int'
1>c:\users\aske\documents\c++\roguelike\roguelike\items.cpp(48): error C2228: left of '.weaponCategory' must have class/struct/union
1>c:\users\aske\documents\c++\roguelike\roguelike\items.cpp(50): error C2228: left of '.at' must have class/struct/union