错误:c ++ [map]没有命名类型

时间:2014-10-19 22:07:12

标签: c++ parsing map enums

我已将以下内容编写为文本冒险游戏的文本命令解析器的一部分。

我试图将用户输入的字符串与枚举类中的项相关联。以下是我的头文件:

#include <iostream>
#include <map>
#include <string>
using namespace std;

enum class Noun
{
    // Interrogation subjects
    name,                   // ask the subject his name
    base,                   // where is the base?
    attack,                 // when will the attack be?

    invalid
};

map < string, Noun > knownNouns;
knownNouns["name"]      = Noun::name;
knownNouns["base"]      = Noun::base;
knownNouns["attack"]    = Noun::attack;

Noun parseNoun(string &noun)
{
    auto n = knownNouns.find(noun);
    if ( n == knownNouns.end() ) {
        return Noun::invalid;
    }
    return n->second;

当我通过编译器时,我得到以下内容:

nouns.h:46:1: error: 'knownNouns' does not name a type
 knownNouns["name"]      = Noun::name;
 ^
nouns.h:47:1: error: 'knownNouns' does not name a type
 knownNouns["base"]      = Noun::base;
 ^
nouns.h:48:1: error: 'knownNouns' does not name a type
 knownNouns["attack"]    = Noun::attack;
 ^
nouns.h: In function 'Noun parseNoun(std::string&)':
nouns.h:52:10: error: 'n' does not name a type
     auto n = knownNouns.find(noun);
          ^
nouns.h:53:10: error: 'n' was not declared in this scope
     if ( n == knownNouns.end() ) {
          ^
nouns.h:54:16: error: 'Noun' is not a class or namespace
         return Noun::invalid;
                ^
nouns.h:56:12: error: 'n' was not declared in this scope
     return n->second;
            ^

这是我第一次尝试使用地图和枚举,而且我不确定我做错了什么。我也不会非常熟悉自动变速器的使用,所以我这方面有点像货物编程。我希望我理解它的实现,一旦解决了我遇到的类型定义问题,错误就会清除。

编辑:那令人尴尬。我复制粘贴了一个我已经纠正过的错误。代码仍然无法编译(即,当发生相同的问题时)

map < string, Noun > knownNouns;
knownNouns["name"]      = Verb::name;
knownNouns["base"]      = Verb::base;
knownNouns["attack"]    = Verb::attack;

更正为

map < string, Noun > knownNouns;
knownNouns["name"]      = Noun::name;
knownNouns["base"]      = Noun::base;
knownNouns["attack"]    = Noun::attack;

2 个答案:

答案 0 :(得分:15)

您不能将非声明构造直接放在命名空间范围内。

C ++翻译单元是一系列声明。

分配等非声明语句必须在函数体内。


固定代码:

#include <iostream>
#include <map>
#include <string>
using namespace std;

enum class Noun
{
    // Interrogation subjects
    name,                   // ask the subject his name
    base,                   // where is the base?
    attack,                 // when will the attack be?

    invalid
};

map< string, Noun > knownNouns = 
{
    { "name", Noun::name },
    { "base", Noun::base },
    { "attack", Noun::attack }
};

auto parseNoun( string const& noun )
    -> Noun
{
    // auto n = knownNouns.find(noun);
    // if ( n == knownNouns.end() ) {
        // return Noun::invalid;
    // }
    // return n->second;
    return Noun::invalid;
}

此处knownNouns 已初始化。即使=看起来非常像作业,也不是作业。

答案 1 :(得分:3)

您可能无法静态初始化地图条目,如:

 knownNouns["name"]      = Verb::name;
 knownNouns["base"]      = Verb::base;
 knownNouns["attack"]    = Verb::attack;