std :: map,带有struct error的值

luk*_*nis 0 c++ visual-c++ c++11 visual-studio-2013

我使用Visual Studio Express 2013,我尝试运行此代码:

struct opcode {
    int length; 
};

std::map<int, struct opcode> opcodes;

opcodes[0x20] = {
    3
};
Run Code Online (Sandbox Code Playgroud)

我收到此错误: error C2040: 'opcodes' : 'int [32]' differs in levels of indirection from 'std::map<int,opcode,std::less<_Kty>,std::allocator<std::pair<const _Kty,_Ty>>>'

当我盘旋过来时,opcodes我得到了这个this declaration has no storage class or type specifier.

我的问题是我把声明放在了函数之外.

AnT*_*AnT 5

在C++语言中 - 即"实际代码" - 必须驻留在函数内部.这个

opcodes[0x20] = {
    3
};
Run Code Online (Sandbox Code Playgroud)

是一份声明.您不能在不声明函数的情况下将其放入文件中.您不能只在文件中间编写C++代码(即语句).

你在函数之间的"空白"所能做的就是写声明.因此,上面的语句被编译器解释为声明.因此来自编译器的奇怪错误消息.

如果您打算将其作为声明,则应该如下所示(例如)

int main()
{
  opcodes[0x20] = { 3 };    
}
Run Code Online (Sandbox Code Playgroud)

但是,通过使用初始化程序,您可以在没有函数的情况下实现相同的效果,初始化程序是声明的一部分

std::map<int, struct opcode> opcodes = { { 0x20, { 3 } } };
Run Code Online (Sandbox Code Playgroud)