错误“xxxx”不为类型命名 [英] Error "xxxx"does not name a type

查看:141
本文介绍了错误“xxxx”不为类型命名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试编译以下代码时遇到问题:

I encountered a problem when tried compiling the following code:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <map>

using namespace std;

map<char, int> mapDial;

mapDial['A'] = 2;

int main()
{

  cout << mapDial['A'] << endl;
  return 0;
}

编译器给了一个错误:'mapDial' 。我是c ++的新手,真的不知道这是怎么回事。这里的任何人都可以帮助我解决这个问题吗?

The compiler gave me a error: 'mapDial' does not name a type error. I am new to c++ and really don't know what is going on here. Can anyone here help me to solve this? Thanks!!

推荐答案

您不能在全局范围执行任意表达式,因此

You cannot execute arbitrary expressions at global scope, so

mapDial['A'] = 2;

是非法的。如果你有C ++ 11,你可以做

is illegal. If you have C++11, you can do

map<char, int> mapDial {
    { 'A', 2 }
};

但是如果没有,你必须从 main ,按照你想要的方式设置它。您还可以查看接受迭代器的 map 的构造函数,并在函数中使用数组来初始化映射,例如

But if you don't, you'll have to call an initialisation function from main to set it up the way you want it. You can also look into the constructor of map that takes an iterator, and use that with an array in a function to initialise the map, e.g.

map<char, int> initMap() {
    static std::pair<char, int> data[] = {
        std::pair<char, int>('A', 2)
    };

    return map<char, int>(data, data + sizeof(data) / sizeof(*data));
}

map<char, int> mapDial = initMap();

这篇关于错误“xxxx”不为类型命名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆