简体   繁体   English

std :: map具有结构错误值

[英]std::map with value of struct error

I use Visual Studio Express 2013 and I try to run this code: 我使用Visual Studio Express 2013,并尝试运行以下代码:

struct opcode {
    int length; 
};

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

opcodes[0x20] = {
    3
};

I get this error: 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>>>' 我收到此错误: 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>>>'

And when I hover over opcodes I get this this declaration has no storage class or type specifier . 当我将鼠标悬停在opcodes时, this declaration has no storage class or type specifier

SOLUTION

The problem of mine was that I have put the statement outside the function. 我的问题是我已将语句放在函数之外。

In C++ language statements - ie "the actual code" - have to reside inside functions. 在C ++语言中,语句(即“实际代码”)必须驻留在函数内部。 This 这个

opcodes[0x20] = {
    3
};

is a statement. 是一个声明。 You cannot just throw it into a file without declaring a function. 您不能不声明函数就将其扔到文件中。 You cannot just write C++ code (ie statements) in the middle of the file. 您不能只在文件中间编写C ++代码(即语句)。

All you can do in the "whitespace" between function is write declarations . 您可以在函数之间的“空白”中做的就是写声明 So, you statement above was interpreted by the compiler as a declaration. 因此,您的上述声明被编译器解释为声明。 Hence the strange error messages from the compiler. 因此,来自编译器的奇怪错误消息。

If you intended this to be a statement, it should have looked as follows (for example) 如果您打算将此作为语句,则它应该看起来如下(例如)

int main()
{
  opcodes[0x20] = { 3 };    
}

However, you could achieve the same effect without a function by using an initializer , which is a part of declaration 但是,通过使用初始化程序 (它是声明的一部分),即使没有函数也可以达到相同的效果。

std::map<int, struct opcode> opcodes = { { 0x20, { 3 } } };

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

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