【问题标题】:ERROR C2039: 'vector': is not a member of 'std'错误 C2039:“向量”:不是“标准”的成员
【发布时间】:2016-09-29 08:25:06
【问题描述】:

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

这是我的头文件之一:(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  

【问题讨论】:

    标签: c++ visual-studio c++11 stdvector


    【解决方案1】:

    在您的 Hero.h 标头中包含 &lt;vector&gt;,并考虑将其从您的 Hero.cpp 文件中删除,如下面的 cmets 所述。

    【讨论】:

    • 不太确定这个答案。在 cpp 文件中,vector 包含在 hero.h 之前,所以应该没问题。您提出的建议是很好的建议,但根据 OP 的信息,这里不会有问题。话虽如此,这种错误几乎总是由缺少标头引起的,因此可能是 OP 的信息不正确。
    • @paxdiablo 是的。我要删除这个答案。
    • @paxdiablo 我们不知道。如果 stdafx.h 包含 hero.h,我不会感到惊讶,导致它在向量之前被解析。
    • stdafx.h 不包括 hero.h
    • 作为一般规则,始终使相应的头文件成为您包含在 cpp 文件中的 first 头文件(除了预编译的头文件,如果您正在使用它们)。这样,当头文件不包含它需要的所有头文件时,您可以确保收到这样的错误。
    【解决方案2】:

    std::vector&lt;Item&gt; items = std::vector&lt;Item&gt;(); 声明了一个完整类型

    因此编译器此时需要知道std::vector声明(除其他外,还需要建立编译时可评估常量sizeof Hero)。解决方法是#include &lt;vector&gt;在标头hero.h不是源文件。

    【讨论】:

      【解决方案3】:
      //.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>
      

      在 2017 年对比测试。 这样,您的自定义头文件中不会包含任何头文件。 但不知道为什么堆栈的保存方式不起作用。

      更多信息,https://github.com/YagaoDirac/snippet-set-for-cpp。还有一个不和谐的链接。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-11
        • 2015-06-22
        • 1970-01-01
        相关资源
        最近更新 更多