错误 C2039:'vector':不是 'std' 的成员

ERROR C2039: 'vector': is not a member of 'std'

我是 C++ 的新手,我正在尝试制作一个地牢爬虫小游戏。目前我在我的头文件中声明了多个向量,但它们似乎给出了多个错误。我曾尝试在 Whosebug 上搜索此问题,但答案似乎并不奏效。

这是我的头文件之一:(Hero.h)

#pragma once

class Hero {
public:
    Hero();
    std::string name;
    int experience;
    int neededExperience;
    int health;
    int strength;
    int level;
    int speed;
    std::vector<Item> items = std::vector<Item>();
    void levelUp();
private:
};

这是我的 .cpp 文件:(Hero.cpp)

#include "stdafx.h"
#include <vector>
#include "Hero.h"
#include "Item.h"

Hero::Hero() {

}
void Hero::levelUp()
{

};

就像我说的,我是 C++ 的新手,所以我的代码可能有比我知道的更多的错误。这只是一个测试。

以下是 Visual Studio 2015 年错误列表中显示的错误:

Error   C2039   'vector': is not a member of 'std'  CPPAssessment   hero.h  13  
Error   C2143   syntax error: missing ';' before '<'    CPPAssessment   hero.h  13  
Error   C4430   missing type specifier - int assumed. Note: C++ does not support default-int    CPPAssessment   hero.h  13  
Error   C2238   unexpected token(s) preceding ';'   hero.h  13  

<vector> 包含在您的 Hero.h header 中,并考虑将其从您的 Hero.cpp 文件,如以下评论所述。

std::vector<Item> items = std::vector<Item>(); 声明一个 完整类型 .

因此,编译器需要知道 std::vector 声明 (除其他事项外,需要建立编译时可计算常量 sizeof Hero).解决办法是#include <vector>在头文件hero.h不是源文件

//.h
template<class _Ty>
class std::allocator;
template<class _Ty, class _Alloc = std::allocator<_Ty> >
class std::vector;

//this line in .cpp file. Put it before custom header files.
#include<vector>

在 vs 2017 中测试。 这样,您的自定义头文件中就没有头文件了。 但是不知道为什么stack的保存方式不起作用

欲了解更多信息,https://github.com/YagaoDirac/snippet-set-for-cpp。和内部的不和谐link。