简体   繁体   English

错误“xxxx”未命名类型

[英]Error “xxxx”does not name a type

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;
}

The compiler gave me a error: 'mapDial' does not name a type error. 编译器给了我一个错误:'mapDial'没有命名类型错误。 I am new to c++ and really don't know what is going on here. 我是c ++的新手,真的不知道这里发生了什么。 Can anyone here help me to solve this? 这里有人可以帮我解决这个问题吗? Thanks!! 谢谢!!

You cannot execute arbitrary expressions at global scope, so 你不能在全局范围内执行任意表达式,所以

mapDial['A'] = 2;

is illegal. 是非法的。 If you have C++11, you can do 如果你有C ++ 11,你可以做到

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

But if you don't, you'll have to call an initialisation function from main to set it up the way you want it. 但是如果你不这样做,你将不得不从main调用初始化函数来按照你想要的方式设置它。 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, eg 您还可以查看带有迭代器的map的构造函数,并将其与函数中的数组一起使用以初始化映射,例如

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();

When you declare a variable in global scope, you may only do initialization. 在全局范围内声明变量时,您可能只进行初始化。 Eg, 例如,

int a = 0;

You cannot do normal statements like: 你不能做正常的陈述,如:

a = 9;

So I would fix the code with: 所以我会修复代码:

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

using namespace std;

map<char, int> mapDial;

int main()
{
  mapDial['A'] = 2;
  cout << mapDial['A'] << endl;
  return 0;
}

You can't have statements like mapDial['A'] = 2; 你不能有像mapDial['A'] = 2;这样的陈述mapDial['A'] = 2; at global scope. 在全球范围内。 They must be inside a function. 它们必须在函数内部。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM