C++:在头文件中声明外部向量容器会导致错误

C++: declaring an extern vector container in header file causes errors

本文关键字:错误 向量 外部 文件 声明 C++      更新时间:2023-10-16

我尝试搜索解决方案,但找不到。

所以我有一个头文件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\roguellike\items.cpp(12):错误C2371:"项目":重新定义;不同的基本类型

1>
c: \users\aske\documents\c++\roguelike\roguellike\items.h(53):请参阅申报"项目"

1> c:\users\aske\documents\c++\roguelike\roguellike\items.cpp(36):错误C2228:".resize"的左侧必须具有类/结构/联合

1> 类型为"int"

1> c:\users\aske\documents\c++\roguelike\roguellike\items.cpp(36):错误C2228:".size"的左侧必须具有类/结构/联合

1> 类型为"int"

1> c:\users\aske\documents\c++\roguelike\roguellike\items.cpp(38):错误C2228:".size"的左侧必须具有类/结构/联合

1> 类型为"int"

1> c:\users\aske\documents\c++\roguelike\roguellike\items.cpp(41):错误C2228:".at"的左侧必须具有类/结构/联合

1> 类型为"int"

1> c:\users\aske\documents\c++\roguelike\roguellike\items.cpp(41):错误C2228:".classification"的左侧必须具有类/结构/联合

1> c:\users\aske\documents\c++\roguelike\roguellike\items.cpp(43):错误C2228:".at"的左侧必须具有类/结构/联合

1> 类型为"int"

1> c:\users\aske\documents\c++\roguelike\roguellike\items.cpp(43):错误C2228:".weaponCategory"的左侧必须具有类/结构/联合

1> c:\users\aske\documents\c++\roguelike\roguellike\items.cpp(46):错误C2228:".at"的左侧必须具有类/结构/联合

1> 类型为"int"

1> c:\users\aske\documents\c++\roguelike\roguellike\items.cpp(46):错误C2228:".weaponCategory"的左侧必须具有类/结构/联合

1> c:\users\aske\documents\c++\roguelike\roguellike\items.cpp(47):错误C2228:".at"的左侧必须具有类/结构/联合

1> 类型为"int"

1> c:\users\aske\documents\c++\roguelike\roguellike\items.cpp(47):错误C2228:".weaponCategory"的左侧必须具有类/结构/联合

1> c:\users\aske\documents\c++\roguelike\roguellike\items.cpp(48):错误C2228:".at"的左侧必须具有类/结构/联合

1> 类型为"int"

1> c:\users\aske\documents\c++\roguelike\roguellike\items.cpp(48):错误C2228:".weaponCategory"的左侧必须具有类/结构/联合

1> c:\users\aske\documents\c++\roguelike\roguellike\items.cpp(50):错误C2228:".at"的左侧必须具有类/结构/联合

items.h文件中,在extern之前需要一个;,然后它应该进行编译,但实际上不需要在.h文件中定义项向量。