使用 new 的矩阵代码中的段错误
我用 C++ 创建了一个简单的类,它有一个私有动态数组。在构造函数中,我使用 new 初始化数组,在析构函数中,我使用 delete 释放它。
当我使用 Class a = Class(..); 实例化该类时它按预期工作,但似乎我无法使用 new 运算符实例化它(如 Class *a = new Class(..);),我总是遇到分段错误。
我不明白的是,什么时候应该使用 new 来实例化一个类,什么时候只调用构造函数,或者是否可以使用 new 或仅调用构造函数来实例化一个类。
float** A = new float*[3];
for (int i=0; i<3; i++) {
A[i] = new float[3];
}
A[0][0] = 3; A[0][1] = 3; A[0][2] = 4;
A[1][0] = 5; A[1][1] = 6; A[1][2] = 7;
A[2][0] = 1; A[2][1] = 2; A[2][2] = 3;
Matrix *M = new Matrix(A, 3, 3);
delete[] A;
delete M;
在类定义下面..
class Matrix
{
private:
int width;
int height;
int stride;
float* elements;
public:
Matrix(float** a, int n, int m);
~Matrix();
};
Matrix::Matrix(float** a, int n, int m)
{
// n: num rows
// m: elem per rows
elements = new float[n*m];
for (int i=0; i<n; i++) {
for (int j=0; j<m; j++) {
elements[i*n + j] = a[n][m];
}
}
}
Matrix::~Matrix()
{
delete[] elements;
}
I created a simple class in C++ which has a private dynamic array. In the constructor I initialize the array using new and in the destructor I free it using delete.
When I instantiate the class using Class a = Class(..); it works as expected, however it seems I cannot instantiate it using the new operator (Like Class *a = new Class(..);), I always get a segmentation fault.
What I don't understand is when I should use new to instantiate a class and when just call the constructor or should it be possible to instantiate a class either with new or by just calling the constructor.
float** A = new float*[3];
for (int i=0; i<3; i++) {
A[i] = new float[3];
}
A[0][0] = 3; A[0][1] = 3; A[0][2] = 4;
A[1][0] = 5; A[1][1] = 6; A[1][2] = 7;
A[2][0] = 1; A[2][1] = 2; A[2][2] = 3;
Matrix *M = new Matrix(A, 3, 3);
delete[] A;
delete M;
Below the class definition..
class Matrix
{
private:
int width;
int height;
int stride;
float* elements;
public:
Matrix(float** a, int n, int m);
~Matrix();
};
Matrix::Matrix(float** a, int n, int m)
{
// n: num rows
// m: elem per rows
elements = new float[n*m];
for (int i=0; i<n; i++) {
for (int j=0; j<m; j++) {
elements[i*n + j] = a[n][m];
}
}
}
Matrix::~Matrix()
{
delete[] elements;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将
i*n + j
替换为i*m + j
。并将
a[n][m]
替换为a[i][j]
Replace
i*n + j
byi*m + j
.and replace
a[n][m]
bya[i][j]