代码之家  ›  专栏  ›  技术社区  ›  killer

地图声明未编译[重复]

  •  0
  • killer  · 技术社区  · 7 年前

    所以出于某种原因,这在类构造函数中有效,但在类外无效,我想知道为什么以及如何让我的映射在类外工作。

    #include <iostream>
    #include <string>
    #include <map>
    
    
    typedef std::map <std::string, int> idMap;
    
    idMap type_id;
    
    
    type_id["Moon"] = 1;
    type_id["Star"] = 2;
    type_id["Sun"] = 3;
    
    
    int main()
    {
    
        std::cout << type_id["Moon"] << std::endl;
    
    }
    

    我得到的编译器错误如下

    11:1: error: 'type_id' does not name a type 12:1: error: 'type_id' does not name a type 13:1: error: 'type_id' does not name a type 
    

    1 回复  |  直到 7 年前
        1
  •  4
  •   gsamaras a Data Head    7 年前

    您的主屏幕应该如下所示:

    int main()
    {
       type_id["Moon"] = 1;
       type_id["Star"] = 2;
       type_id["Sun"] = 3;
       std::cout << type_id["Moon"] << std::endl;
    }
    

    您不能将这些语句放在函数之外(在这种情况下 main()


    或者如果你真的想在外面填充地图

    idMap type_id { {"Moon", 1}, {"Star", 2}, {"Sun", 3} };
    

    这种方法也适用于头文件,如下所示:

    我的标题。h

    #include <string>
    #include <map>
    
    typedef std::map <std::string, int> idMap;
    
    idMap type_id { {"Moon", 1}, {"Star", 2}, {"Sun", 3} };
    

    #include <iostream>
    #include "myHeader.h"
    
    int main() {
        std::cout << type_id["Moon"] << std::endl;
    }