【问题标题】:conflicting declaration when filling a static std::map class member variable填充静态 std::map 类成员变量时声明冲突
【发布时间】:2010-05-28 20:30:07
【问题描述】:

我有一个带有静态 std::map 成员变量的类,它将 chars 映射到自定义类型 Terrain。我试图在类的实现文件中填充这个映射,但我得到了几个错误。这是我的头文件:

#ifndef LEVEL_HPP
#define LEVEL_HPP

#include <bitset>
#include <list>
#include <map>
#include <string>
#include <vector>
#include "libtcod.hpp"

namespace yarl
{
    namespace level
    {
        class Terrain
        {
        // Member Variables
            private:
               std::bitset<5> flags;

        // Member Functions
            public:
                explicit Terrain(const std::string& flg)
                : flags(flg) {}

            (...)
        };



        class Level
        {
            private:
                static std::map<char, Terrain> terrainTypes;

            (...)
        };
    }
}

#endif 

这是我的实现文件:

#include <bitset>
#include <list>
#include <map>
#include <string>
#include <vector>
#include "Level.hpp"
#include "libtcod.hpp"
using namespace std;

namespace yarl
{
    namespace level
    {
        /* fill Level::terrainTypes */
        map<char,Terrain> Level::terrainTypes['.'] = Terrain("00001");  // clear
        map<char,Terrain> Level::terrainTypes[','] = Terrain("00001");  // clear 
        map<char,Terrain> Level::terrainTypes['\''] = Terrain("00001"); // clear
        map<char,Terrain> Level::terrainTypes['`'] = Terrain("00001");  // clear
        map<char,Terrain> Level::terrainTypes[178] = Terrain("11111");  // wall

        (...)
    }
}

我正在使用 g++,我得到的错误是

src/Level.cpp:15:错误:冲突声明'std::map,std::allocator >> yarl::level::Level::terrainTypes [46]'
src/Level.hpp:104: 错误: 'yarl::level::Level::terrainTypes' 之前的声明为'std::map, std::allocator > > yarl::level::Level::terrainTypes'
src/Level.cpp:15: 错误:在类外声明“std::map, std::allocator >> yarl::level::Level::terrainTypes”未定义
src/Level.cpp:15:错误:从“yarl::level::Terrain”转换为非标量类型“std::map, std::allocator >>”请求
src/Level.cpp:15: error: ‘yarl::level::Level::terrainTypes’在声明时不能被非常量表达式初始化

我为实现文件中的每个映射分配行获得了一组这些。有人看到我做错了什么吗?感谢您的帮助。

【问题讨论】:

    标签: c++ map static-members


    【解决方案1】:

    您可以在函数之外初始化静态成员,但不能执行任意操作。

    您可以使用函数来初始化成员:

    namespace {
        std::map<char, Terrain> initTerrainTypes() {
            std::map<char, Terrain> m;
            m['.'] = Terrain("00001"); 
            // ...
            return m;
        }
    }
    
    map<char,Terrain> Level::terrainTypes = initTerrainTypes();
    

    或者您可以使用初始化实用程序,例如 Boost.Assign:

    map<char,Terrain> Level::terrainTypes = boost::assign::map_list_of
       ('.', Terrain("00001"))
       // ...
       (178, Terrain("11111"));
    

    【讨论】:

    • 第一个选项解决了这个问题。感谢您的帮助。
    猜你喜欢
    • 2017-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-07
    相关资源
    最近更新 更多