gpt4 book ai didi

c++ - 使用类作为 STL 映射的类型

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:54:14 31 4
gpt4 key购买 nike

我使用的是 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( );
};

map 中使用的类:

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

我正在尝试将一个对象插入到 map 中:

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:\Programms\Embarcadero\RAD Studio\8.0\include\boost_1_39\boost\tr1\tr1\map
map(20): #include C:\Programms\Embarcadero\RAD Studio\8.0\Quickrep505C\../include/dinkumware/map
map(5): #include c:\Programms\embarcadero\rad studio\8.0\include\dinkumware\xtree
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就没有这个问题。将类用作 map 中的值是否有某种要求?

最佳答案

我可以看到一些小问题

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

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

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

为了能够将元素作为值放入映射中,类必须是可分配的、可复制构造的并且也是可默认构造的(operator[] 需要能够默认构造一个元素) 在这种情况下一切似乎都正常。

不幸的是,众所周知,C++ 编译器会在您进入模板领域时生成几乎无用的错误消息。

关于c++ - 使用类作为 STL 映射的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22608377/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com