我遇到了一个我认为与创建对象副本有关的问题。我有一个映射类,它包含一个std :: map,其中有一些类定义由它们的ID索引的不同tile类型,以及向量中的一堆tile,每个tile都有一个指向其中一个类的指针。此外,我还有另一个课程Scenario,其中包含地图。复制后访问对象时C++程序崩溃
当我创建一个Scenario对象并尝试用它的地图做任何事情时,问题就出现了。复制指针时肯定会出现一些问题,但我一直无法弄清楚。
我试图减少代码到什么必要来重现问题:
#include <string>
#include <map>
#include <vector>
#include <iostream>
using namespace std;
class TileInfo {
string name;
public:
int id;
TileInfo() {};
TileInfo(int id, string name);
string getName() const;
};
TileInfo::TileInfo(int id, string name)
{
this->id = id;
this->name = name;
}
string TileInfo::getName() const
{
return name;
}
class Tile
{
public:
TileInfo* info;
Tile() {};
Tile(const Tile & other, map<int,TileInfo> & info);
Tile (TileInfo* info);
string getName() const;
};
Tile::Tile (TileInfo* tileInfo)
{
this->info = tileInfo;
}
Tile::Tile(const Tile & other, map<int,TileInfo> & tileInfo)
{
map<int,TileInfo>::iterator it = tileInfo.find(other.info->id);
if(it == tileInfo.end())
this->info = NULL;
else
this->info = &(it->second);
}
string Tile::getName() const
{
return info->getName();
}
class Map
{
vector <vector <Tile>> tiles;
map <int, TileInfo> tileInfo;
public:
void print() const;
Map() {};
Map(map<int,TileInfo> tileInfo);
Map(const Map & other);
string getName() const;
void loadTiles();
};
Map::Map(map<int,TileInfo> tileInfo)
{
this->tileInfo = tileInfo;
}
Map::Map(const Map & other)
{
this->tileInfo = other.tileInfo;
for(unsigned int i = 0; i < other.tiles.size(); i++)
{
vector<Tile> line;
for(unsigned int j = 0; j < other.tiles[i].size(); j++)
{
Tile tmpTile = Tile(other.tiles[i][j],tileInfo);
line.push_back(tmpTile);
}
this->tiles.push_back(line);
}
}
void Map::print() const
{
for(unsigned int i = 0; i < tiles.size(); i++)
{
for(unsigned int j = 0; j < tiles[i].size(); j++)
{
cout << "Tile at " << i << ", " << j << " is a "; cout << tiles[i][j].getName() << endl;
}
}
}
void Map::loadTiles()
{
for(unsigned int i = 0; i < 3; i++)
{
vector <Tile> line;
for(unsigned int j = 0; j < 3; j++)
{
map<int,TileInfo>::iterator ite = tileInfo.find(i);
if(ite!=tileInfo.end())
line.push_back(Tile(&(ite->second)));
else
{
line.push_back(Tile(NULL));
}
}
tiles.push_back(line);
}
}
class Scenario
{
public:
Map map;
Scenario() {};
Scenario(Map map);
};
Scenario::Scenario(Map map)
{
this->map = map;
this->map.print();
}
Map createMap()
{
map<int,TileInfo> tmpInfo;
for(unsigned int i = 0; i < 3; i++)
{
tmpInfo.insert(pair<int,TileInfo>(i,TileInfo(i,"testname")));
}
Map rtrnVal = Map(tmpInfo);
rtrnVal.loadTiles();
return rtrnVal;
}
int main()
{
Map newMap = createMap();
Scenario newScenario = Scenario(newMap);
newScenario.map.print();
int input;
cin >> input;
}
打印()在场景构造结束正确打印地图的内容,但该方案后,一个是分配导致崩溃。任何帮助,将不胜感激。
这是很多代码,你没有正确实现拷贝构造函数,没有检查空指针和各种*坏事*。你应该使用一个调试器来调试你的代码,它应该揭示出现问题的地方...... – Nim
'场景* newScenario = new Scenario(newMap);'''newScenario-> map.print();'请尝试。 –
没有看到任何错误。在这里添加了你的代码.http://ideone.com/ivVFwd – shivakumar