使用类作为STL映射的类型

Using a class as the type for STL map

本文关键字:映射 类型 STL      更新时间:2023-10-16

我使用的是Embarcadero c++ Builder XE, Windows 7, 32位。我有问题编译代码使用类作为STL映射的类型。在我的简单测试示例中,类声明如下:

#include <map>
class TMyClass
{
private:    // User declarations
 int cVal1;
 int cVal2;
public:
    TMyClass& __fastcall operator = ( TMyClass& aMyClassObj);
public:     // User declarations
    __fastcall TMyClass( void);
    __fastcall TMyClass( int aVal1, int aVal2);
    __fastcall TMyClass( const TMyClass& aMyClassObj);  // copy constructor 1
    __fastcall TMyClass(       TMyClass& aMyClassObj);     // copy constructor 2
    __fastcall ~TMyClass( );
};

类在映射中使用:

typedef std::map< int, TMyClass>  TMyMap;

我正在尝试插入一个对象到映射:

TMyMap  sMyMap;
TMyClass     sMyClassObj( 10, 10);
aMyMap[ 1] = sMyClassObj;

最后一行给出了编译错误:

[BCC32 Error] xtree(29): E2285 Could not find a match for 'pair<const int,TMyClass>::pair(const pair<const int,TMyClass>)'
  Full parser context
    xtree(28): decision to instantiate:  _Tree_nod<_Tmap_traits<int,TMyClass,less<int>,allocator<pair<const int,TMyClass> >,0> >::_Node::_Node(_Tree_nod<_Tmap_traits<int,TMyClass,less<int>,allocator<pair<const int,TMyClass> >,0> >::_Node *,_Tree_nod<_Tmap_traits<int,TMyClass,less<int>,allocator<pair<const int,TMyClass> >,0> >::_Node *,_Tree_nod<_Tmap_traits<int,TMyClass,less<int>,allocator<pair<const int,TMyClass> >,0> >::_Node *,const pair<const int,TMyClass> &,char)
    --- Resetting parser context for instantiation...
    U_TestKompilacji.cpp(10): #include U_TestKompilacji.h
    U_TestKompilacji.h(5): #include C:ProgrammsEmbarcaderoRAD Studio8.0includeboost_1_39boosttr1tr1map
    map(20): #include C:ProgrammsEmbarcaderoRAD Studio8.0Quickrep505C../include/dinkumware/map
    map(5): #include c:Programmsembarcaderorad studio8.0includedinkumwarextree
    xtree(8): namespace std
    xtree(13): class _Tree_nod<_Traits>
    xtree(25): class _Tree_nod<_Traits>::_Node
    xtree(28): parsing:  _Tree_nod<_Tmap_traits<int,TMyClass,less<int>,allocator<pair<const int,TMyClass> >,0> >::_Node::_Node(_Tree_nod<_Tmap_traits<int,TMyClass,less<int>,allocator<pair<const int,TMyClass> >,0> >::_Node *,_Tree_nod<_Tmap_traits<int,TMyClass,less<int>,allocator<pair<const int,TMyClass> >,0> >::_Node *,_Tree_nod<_Tmap_traits<int,TMyClass,less<int>,allocator<pair<const int,TMyClass> >,0> >::_Node *,const pair<const int,TMyClass> &,char)
许多天来我一直在寻找解决办法。在Borland c++ Builder 6.0中没有这样的问题,我以前使用过它。类作为映射中的值是否有某种要求?

我可以看到一些小问题

  1. 默认构造函数应该声明为TMyClass()(没有void)。这只是一个风格问题(函数声明的空括号/void区别是针对C的,而不是c++的)。

  2. 为什么constTMyClass&的复制构造函数不同?

  3. 为什么有那么多__fastcall的噪音?这是我要删除的第一件事,看看它是否有问题。

为了能够将一个元素作为映射中的值,类必须是可赋值的、可复制构造的和默认构造的(operator[]需要能够默认构造一个元素),在这种情况下,这一切似乎都是可以的。

不幸的是,当您进入模板领域时,c++编译器以产生几乎无用的错误消息而闻名。