你好:)我是一个非常新的程序员,不知道为什么我有这个错误。为了解释,当我运行该程序与在线路不同的值(下面的代码)程序编译但偶尔会引起崩溃的原因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感谢您让我知道 - 我将删除该部分并研究! –