我正在尝试在 C++ 上制作一个小游戏,并且我正在尝试重载“=”运算符。它应该复制游戏,并使副本不可靠。看起来我的内存有问题或类似的东西,因为当我尝试打印副本时它崩溃了。我究竟做错了什么? 这是重载:
Game& Game::operator=(const Game& other){
std::vector<Pair> new_grid;
for(int i=0; i < other.grid_characters.size(); i++){
Character* character = other.grid_characters[i].character->clone();
std::shared_ptr<Character> character_shared_ptr(character);
Pair new_element( other.grid_characters[i].grid_point, character_shared_ptr);
new_grid.push_back(new_element);
}
this->height=other.height;
this->width = other.width;
this->grid_characters=new_grid;
return *this;
}
重载“<<”:
std::ostream& operator<<(std::ostream& os, const Game& game){
std::string grid_str_to_print;
for(int i=0; i < game.height; i++){
for(int j=0; j < game.width; j++){
GridPoint grid_point(i, j);
std::shared_ptr<Character> character = getCharacterAtPoint(game, grid_point);
if(character == nullptr){
grid_str_to_print += ' ';
} else {
grid_str_to_print += character->getCharSymbol();
}
}
}
char* output_grid = new char[grid_str_to_print.length() +1];
strcpy(output_grid, grid_str_to_print.c_str());
printGameBoard(os,output_grid, output_grid + grid_str_to_print.length() ,game.width);
delete[] output_grid;
return os;
}
并印刷电路板:
std::ostream &mtm::printGameBoard(std::ostream &os, const char *begin,
const char *end, unsigned int width) {
std::string delimiter = std::string(2 * width + 1, '*');
const char *temp = begin;
os << delimiter << std::endl;
while (temp != end) {
os << "|" << (*temp);
++temp;
if ((temp - begin) % width == 0)
os << "|" << std::endl;
}
os << delimiter;
return os;
}
这是一对:
struct Pair {
GridPoint grid_point;
std::shared_ptr<Character> character;
Pair(GridPoint grid_point, std::shared_ptr<Character> character) :
grid_point(grid_point), character(character) {}
};
这是克隆:
Character* Soldier::clone() const {
return new Soldier(*this);
}
这是主要的代码:
#include <iostream>
#include <cassert>
#include "Exceptions.h"
#include "Game.h"
using namespace mtm;
void example1() {
std::cout << "------example 2------" << std::endl;
Game g1(5,10);
g1.addCharacter(GridPoint(3,0), Game::makeCharacter(CharacterType::SOLDIER, Team::POWERLIFTERS, 20, 0, 3, 5));
Game g2 = g1;
std::cout << g1 << std::endl;
std::cout << g2 << std::endl;
std::cout << "Nice!" << std::endl;
}
int main() {
example1();
return 0;
}
没有返回错误,也没有任何消息。