本文介绍了std :: map问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的地图:


std :: map< string,CObject> ObjectList;


我有这样的函数:


CObject * NewObject(char * Name,CArg * Arg)

{

std :: string key = Name;

ObjectList [key] = CObject(Name,Arg);

return& ; ObjectList [Name];

}


我试图编译它抱怨没有默认构造函数

for CObject


所以我将构造函数声明更改为:

CObject :: CObject(char * Name =" Default",CArg * Arg = NULL);


只是因为我没有有效的CArg指针就无法创建它。


当我调用NewObject时它会编译崩溃,我看到它的调试器

似乎首先用正确的参数调用构造函数,然后

再次调用它而没有参数(在这种情况下使我的程序崩溃) ,

但我不明白为什么。


如果有人能解释我不知道的是什么站在这里....


另一个快速的问题,如果名称确实& ObjectList [Name]返回NULL

与地图中的键不匹配?


感谢advanec。

Well I have a map like this :

std::map <string, CObject> ObjectList;

I have a function like this :

CObject* NewObject( char* Name, CArg* Arg)
{
std::string key = Name;
ObjectList[ key] = CObject( Name, Arg);
return &ObjectList[Name];
}

I tried to compile and it complained that there was no default constructor
for CObject

So I changed my constructor declaration to :
CObject::CObject( char* Name = "Default", CArg* Arg = NULL);

Just to sse because I can''t create it without a valid CArg pointer.

it compiles when I call NewObject it crashes, with the debugger I saw it
seemed to call the constructor with the correct arguments first, and then
call it again with no arguments (which in this case makes my program crash),
but I don''t understant why.

If someon ecould explain what I don''t understand here....

An other quick question, does &ObjectList[ Name] return NULL if Name does
not match a key in the map ?

Thanks in advanec.

推荐答案




否。它插入一个新对象并返回对它的引用。 RTFM。


Victor



No. It inserts a new object and returns a reference to it. RTFM.

Victor





不,在这种情况下,operator []会在地图中插入一个新的键值对,并且

你获取指向默认构造的CObject实例的指针。


-

David Hilsee



No, in that case, operator[] inserts a new key-value pair into the map and
you get a pointer to the default-constructed CObject instance.

--
David Hilsee





再次,这应该读作复制品。


-

David Hilsee



Again, that should read "to a copy of the".

--
David Hilsee


这篇关于std :: map问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-15 04:58