我正在編寫一個程序來顯示康威的C++生命遊戲。我的教授給了我們一個描述「宇宙」的主要功能和類別,我們必須實現課堂上原型的功能。我現在的問題實際上是讓構造函數運行。我將發佈該類,然後是我爲構造函數編寫的內容。使用GDB,當我到達使用構造函數的第一行時(universe(width,height,wrap);)我得到以下錯誤:libC++ abi.dylib:terminate調用拋出異常構造函數不工作
編程接收信號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 2013-04-18 02:11:23
你是否看到3-param構造函數在它們被實際分配之前分配一個本地數組(並且從不分配它,因此泄漏它)你的**成員**'width'和'height' * *當這個ctor完成時,你有'array'的不確定值,未定義大小的內存泄漏,以及分配的寬度+高度值。 – WhozCraig 2013-04-18 02:13:09
您應該閱讀關於C++的一些文章/書籍。這段代碼就像C和C++的一些怪誕的愛情小孩。 RAII,容器和初始化列表是你的朋友。 – 2013-04-18 02:14:54