Я пишу программу, чтобы показать Game of Life от Conway в C++. Мой профессор дал нам основную функцию и класс, описывающий «вселенную», мы должны реализовать функции, прототипированные в классе. Моя проблема сейчас заключается в том, чтобы заставить конструктор функционировать. Я опубликую класс, а затем напишу для конструктора. Использование GDB, когда я добираюсь до первой строки, используемой конструктором (юниверс (ширина, высота, обертка);) Я получаю следующую ошибку: libC++ abi.dylib: terminate called throwing exceptionКонструктор не работает
Полученный сигнал программы SIGABRT, Прервано. 0x00007fff876fad46 in __kill()
Любая помощь приветствуется! Код ниже.
// Conways game of life
class universe {
private:
int* array; // A pointer to a [width]X[height] array of cells that constitutes the universe
// for the game of life. A value of 1 signifies a live cell at that location.
int width; // The width of the universe.
int height; // The height of the universe
int wrap; // wrap = 1 means the universe wraps around on itself -- the right hand
// side connects to the left and the top connects to the bottom.
// wrap = 0 means the universe ends at the array boundaries.
public:
universe(); // A null constructor: sets array, width, height, and wrap to 0.
universe(int,int,int); // Constructor to allocate space for a universe of given width (first value)
// height (second value) and wrap setting (third value). Sets all cells to 0.
void display(); // Display the live cells in a graphics window.
void setup(); // Display the universe then allow the user to interactively modify
// the cell arrangement using the mouse.
void operator<<(char*); // Read in a universe from a file; first number has the width,
// second number is the height,
// third number is the wrap parameter,
// then 1s/0s in a 2D integer array represent living/dead cells.
void operator>>(char*); // Save the universe to a file with the specified name (format as above).
void operator=(universe); // Copy the contents of one universe to another.
void operator<<(universe); // Calculate the new generation by applying the rules, then
// display the new generation.
int neighbors(int,int); // Returns the number of neighbors of the cell at i,j.
int value(int,int); // Returns the value at cell i,j (0 or 1).
void setvalue(int,int,int); // Sets the value of the cell at i,j.
void free(); // Release the memory used to store the universe. Set array = 0.
};
// Implementation
universe::universe(){
array =0;
width = 0;
height = 0;
wrap = 0;
}
universe::universe(int width1,int height1,int wrap1){
int i=0, j=0;
int* array = new int[width*height-1];
for(i=0;i<width;i++){
for(j=0;j<height;j++){
array[j*width+i] =0;
}
}
width = width1;
height =height1;
wrap = wrap1;
}
Вам не хватает конструктора копирования и деструктора (функции 'free()' делают ** не ** сокращают его). Кроме того, я бы предложил контейнер, но я готов поспорить, что вам запрещено использовать его. – chris
Вы видите конструктор с 3 параметрами, который выделяет локальный массив (и никогда не назначает его, тем самым утечка) ваших ** членов ** 'width' и' height' * before * они фактически назначены? Когда это завершено, у вас есть неопределенное значение для 'array', утечка памяти неопределенного размера и назначенные значения ширины и высоты. – WhozCraig
Вы должны прочитать некоторые статьи/книги на C++. Этот код похож на какого-то гротескного любовного ребенка C и C++. RAII, контейнеры и списки инициализации - ваши друзья. –