我得到一個段錯誤,我創建一個C++字符串與複製構造函數。我查看了一些類似的問題,但都是因爲傳入了一個錯誤的C++字符串對象。我只是傳入一個原始字符串,所以我不確定我的問題是什麼。我將粘貼相關的代碼片段(它來自多個不同的文件,因此可能看起來有點混亂)。段錯誤發生在Species類的默認構造函數的第4行。段錯誤複製構造函數爲字符串
Species::Species(string _type) {
program_length = 0;
cout << _type << " 1\n";
cout << type << " 2\n";
type = string(_type);
}
Grid::Grid(int _width, int _height) {
*wall = Species("wall");
*empty = Species("empty");
turn_number = 0;
width = _width;
height = _height;
for(int a= 0; a < 100; a++)
for(int b = 0; b< 100; b++) {
Creature empty_creature = Creature(*empty,a,b,NORTH,this);
(Grid::map)[a][b] = empty_creature;
}
}
int main() {
Grid world = Grid(8,8);
}
class Grid {
protected:
Creature map[100][100];
int width,height;
int turn_number;
Species *empty;
Species *wall;
public:
Grid();
Grid(int _width, int _height);
void addCreature(Species &_species, int x, int y, Direction orientation);
void addWall(int x, int y);
void takeTurn();
void infect(int x, int y, Direction orientation, Species &_species);
void hop(int x, int y, Direction orientation);
bool ifWall(int x, int y, Direction orientation);
bool ifEnemy(int x, int y, Direction orientation, Species &_species);
bool ifEmpty(int x, int y, Direction orientation);
void print();
};
class Species {
protected:
int program_length;
string program[100];
string type;
public:
species(string _type);
void addInstruction(string instruction);
bool isWall();
bool isEmpty();
bool isEnemy(Species _enemy);
string instructionAt(int index);
string getType();
};
這是我更新後的代碼,我從牆上刪除指針和空指針。現在我得到一個奇怪的錯誤(「錯誤:場牆面不網格成員」):
Grid::Grid(int _width, int _height) {
(Grid::wall) = Species("wall");
(Grid::empty) = Species("empty");
cout << (*wall).getType() << "\n";
turn_number = 0;
width = _width;
height = _height;
for(int a= 0; a < 100; a++)
for(int b = 0; b< 100; b++) {
Creature empty_creature = Creature(Grid::empty,a,b,NORTH,this);
(Grid::map)[a][b] = empty_creature;
}
}
class Grid {
protected:
Creature map[100][100];
int width,height;
int turn_number;
Species empty;
Species wall;
public:
Grid();
Grid(int _width, int _height);
void addCreature(Species &_species, int x, int y, Direction orientation);
void addWall(int x, int y);
void takeTurn();
void infect(int x, int y, Direction orientation, Species &_species);
void hop(int x, int y, Direction orientation);
bool ifWall(int x, int y, Direction orientation);
bool ifEnemy(int x, int y, Direction orientation, Species &_species);
bool ifEmpty(int x, int y, Direction orientation);
void print();
};
在你的類定義,種類寫小寫,C++是區分大小寫的。 (這次發表評論) –