首页 文章

std :: map中的项目错误

提问于
浏览
0

我有这两个文件:

Circles.h

#ifndef CIRCLE_H
#define CIRCLE_H
#include <map>
using namespace std;

map<int, int> colormap;

#endif

main.cpp

#include <iostream>
#include "Circles.h"
using namespace std;

int main ()
{
     int a;
     cin>>a;
     cout<<a<<endl;
     return 0;
}

错误:

|| === Build:在Mulit-game中调试(编译器:GNU GCC编译器)=== | obj \ Debug \ main.o ||在函数ZSt11__addressofISt4pairIKiN2sf5ColorEEEPT_RS5 _':| D:\ SFML Projects \ Mulit-game \ main.cpp | 7 | colormap'|的多重定义obj \ Debug \ Circles.o:c:\ program files(x86)\ codeblocks \ mingw \ lib \ gcc \ mingw32 \ 4.8.1 \ include \ c \ mingw32 \ bits \ gthr-default.h | 300 |首先在这里定义| || ===构建失败:2个错误,0个警告(0分钟,0秒(秒))=== |

我不知道它为什么这样做,因为我搜索了我的项目的所有文件, Map 只能在 Circles.h 中找到 .

3 回答

  • 0

    不要在头文件中声明全局变量 .

  • 1

    我假设 Map 实际上被称为 colormap ,并且头文件包含在多个源文件中?因为这是获得该错误的唯一方法 .

    问题是您在头文件中定义变量 colormap ,因此它将在包含标头的每个源文件中定义 .

    相反,您应该只在头文件中进行外部声明,并在一个源文件中进行定义 .


    因此,在头文件中,例如,

    extern std::map<int, int> colormap;  // Declare the colormap variable
    

    在您的一个源文件中,在全局范围内:

    std::map<int, int> colormap;  // Define the colormap variable
    
  • 7

    不确定为什么你的代码不起作用 . 我在Visual Studio中编写它并且构建得很好 . 您正在使用gcc编译器,这可能更严格 . 我建议你不要在你的代码中使用“using namespace std”两次 . 说实话,我建议不要使用“using namespace std” . 而是在声明 Map 时,请执行以下操作:

    std::map<int,int> myMap;
    

    此外,如果您有一个全局变量(在您的情况下为colormap),最好将其声明为不在您定义类的文件中(在您的情况下为Circles?) .

相关问题