你好:)我是一個非常新的程序員,不知道爲什麼我有這個錯誤。爲了解釋,當我運行該程序與在線路不同的值(下面的代碼)程序編譯但偶爾會引起崩潰的原因255(CodeBlocks)
array2D *a = new array2D(320,240);
(例如,改變320和240,以32和24)中的程序或者在執行的getSize功能之後的某個時間或之後崩潰執行prtValue函數(更常見的是前者)。但是,當我構建代碼時,無論我在上面的行中具有哪些值,它都會返回0個錯誤和0個警告。
我測試了cpp.sh上的代碼,該網站準確地更改了值並每次輸出正確/完整的結果,所以我想知道這是否是CodeBlocks /我的硬件問題?調試器也只返回一個問題,它似乎與setValue函數,但我未經訓練的眼睛不能說出了什麼問題。
無知的道歉。再次,我幾乎沒有這方面的經驗,有點不知所措。提前感謝您提供的任何幫助。
#include <iostream>
using namespace std;
class array2D
{
protected:
int xRes;
int yRes;
float ** xtable;
public:
array2D (int xResolution, int yResolution);
void getSize(int &xResolution, int &yResolution);
void setValue(int x,int y,float val);
float getValue(int x,int y);
~array2D();
};
array2D::array2D(int xResolution, int yResolution)
{
xRes=xResolution;
yRes=yResolution;
xtable = new float*[xResolution];
for(int i=0;i < xResolution;i++)
{
xtable[i] = new float[yResolution];
}
for(int i=0;i < xRes;i++)
{
for(int j=0;j < yRes;j++)
{
xtable[i][j]=0;
}
}
}
void array2D::getSize(int &xResolution, int &yResolution)
{
xResolution=xRes;
yResolution=yRes;
cout << "Size of Array (rows, columns): " << xResolution << ", " << yResolution << endl;
}
void array2D::setValue(int x,int y,float val)
{
xtable[x][y] = val;
}
float array2D::getValue(int x,int y)
{
return xtable[x][y];
}
array2D::~array2D(){
cout << "Destructing array" << endl;
}
int main()
{
array2D *a = new array2D(32,24);
int xRes, yRes;
a->getSize(xRes,yRes);
for(int i=0;i < yRes;i++)
{
for(int j=0;j < xRes;j++)
{
a->setValue(i,j,100.0);
}
}
for(int j=0;j < xRes;j++)
{
for(int i=0;i < yRes;i++)
{
cout << a->getValue(i,j) << " ";
}
cout << endl;
}
a->~array2D();
}
手動調用析構函數幾乎總是一個壞主意。我想你的意思是'刪除一個''在那裏結束。 – user4581301
推薦閱讀[三條法則是什麼?](https://stackoverflow.com/questions/4172722/what-is-the-rule-of-ree)稍後會節省很多混亂。 – user4581301
@ user4581301感謝您讓我知道 - 我將刪除該部分並研究! –