【发布时间】:2015-11-19 02:18:19
【问题描述】:
如果我有一个带有地图的类作为私有成员,例如
class MyClass
{
public:
MyClass();
std::map<std::string, std::string> getPlatforms() const;
private:
std::map<std::string, std::string> platforms_;
};
MyClass::MyClass()
:
{
platforms_["key1"] = "value1";
// ...
platforms_["keyN"] = "valueN";
}
std::map<std::string, std::string> getPlatforms() const
{
return platforms_;
}
在我的主函数中,这两段代码会有区别吗?
代码1:
MyClass myclass();
std::map<std::string, std::string>::iterator definition;
for (definition = myclass.getPlatforms().begin();
definition != myclass.getPlatforms().end();
++definition){
std::cout << (*definition).first << std::endl;
}
代码2:
MyClass myclass();
std::map<std::string, std::string> platforms = myclass.getPlatforms();
std::map<std::string, std::string>::iterator definition;
for (definition = platforms.begin();
definition != platforms.end();
++definition){
std::cout << (*definition).first << std::endl;
}
在 Code2 中,我刚刚创建了一个新的地图变量来保存从 getPlatforms() 函数返回的地图。
无论如何,在我的真实代码中(我无法从中发布真实代码,但它直接对应于这个概念)第一种方式(代码 1)会导致运行时错误,无法访问某个位置的内存。
第二种方法有效!
您能告诉我这两段不同代码之间发生了什么的理论基础吗?
【问题讨论】:
标签: c++ dictionary iterator