【问题标题】:C++ map from std::pair to some internal class从 std::pair 到某个内部类的 C++ 映射
【发布时间】:2013-07-29 08:42:19
【问题描述】:

设置

#include<utility> // I actually use precompiled headers 
#include<map>
...SOME CODE...
namespace{
... SOME CODE...
/*Line 278*/ std::map<std::pair<int,int>,SmartPointer<A>> myMap;
/*Line 279*/ myMap.at(std::make_pair(1,1));
}

SmartPointer 就是所说的 - 一个使用智能指针包装其他类的类,用于自动堆内存管理。

发生的情况是,当我尝试编译它时,我得到了一大堆错误:

cpp(279): error C2143: syntax error : missing ';' before '.'
cpp(279): error C4430: missing type specifier - int assumed. Note: C++ does not 
support default-int
cpp(279): error C2371: '`anonymous-namespace'::map' : 
redefinition; different basic types
cpp(278) : see declaration of '`anonymous-namespace'::map'

第 278 和 279 行是上面的代码行。

map 位于匿名命名空间中,可以看出。我怀疑这是因为内部映射未配置为接受非标准类型作为值。

这一切都发生在 VS 2010 + 我也在使用 C++11。

问题

为什么会出现这些编译错误以及如何修复它们?

进展

&gt;&gt; 不是问题 - 当我注释掉第二行时,文件编译时不会抱怨(&gt;&gt;&gt; &gt;)。

我将代码简化为这个 - 看看错误可能来自哪里 - 我得到以下一组编译错误:

代码:

std::map < int, int > myMap;
myMap[3] = 4;

错误:

cpp(279): error C4430: missing type specifier - int assumed. Note: C++ does not 
support default-int
cpp(279): error C2373: 'myMap' : redefinition; different type modifiers
cpp(278) : see declaration of 'myMap'
cpp(279): error C2440: 'initializing' : cannot convert from 'int' to 'int [3]'
There are no conversions to array types, although there are conversions 
to references or pointers to arrays

回答

@凯西

根据 Casey 的建议,我不能将 myMap.at(..) 放在命名空间范围内 - 我将它放在函数范围内,它得到了修复。

【问题讨论】:

  • 那是因为您在&gt;&gt; 之间缺少一个空格:std::map&lt;std::pair&lt;int,int&gt;,SmartPointer&lt;A&gt;/*HERE*/ &gt; map;
  • 编译器可能将>>解析为操作符。
  • 不是!它与&gt;&gt; 编译得很好,但我还是改变了它并且错误仍然存​​在。
  • 您不能只将map.at(...) 放在命名空间范围内,它需要在函数内部。
  • 它刚刚编译 - 点了

标签: c++ visual-studio-2010 visual-c++ c++11 map


【解决方案1】:

只是不要将标准库名称(例如 map)用于变量名称。称它为something有意义,它也会消除类型和变量之间的冲突。

另外,你忘了#include &lt;utility&gt; 引入std::pair

【讨论】:

  • 我使用预编译的头文件(stdafx,里面有#include&lt;utility&gt;),为了清楚起见,我重命名了我的变量map - 在内部它被称为别的东西,因为我不想透露更多信息关于我的实现。
  • 但是,我会重命名我发布的源代码,以便人们阅读时清楚
【解决方案2】:

你有名字冲突:

std::map<std::pair<int,int>,SmartPointer<A>> map;

名称map 是类型。您不能将类型名称用作变量名称。类似的东西

std::map<std::pair<int,int>,SmartPointer<A>> myMapThatHasAUsefullName;

应该修复它。

【讨论】:

  • 抱歉 - 我在内部使用了不同的名称,现在我将变量重命名为 myMap 以清楚起见。但问题不在于——这是因为我无法在命名空间级别调用 myMap.at(..)
猜你喜欢
  • 1970-01-01
  • 2016-04-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-16
  • 1970-01-01
  • 2011-01-01
相关资源
最近更新 更多