我不知道如何解决这个问题,下面是一个非常简单的类,它将2D动态数组和大小存储到一个对象(矩阵)中。我的问题是初始化其中一些类不起作用,除非我调用成员函数。我缩小了问题的范围,这是导致这种情况的析构函数。
Square_Matrix a; //works
Square_Matrix b;
Square_Matrix a,b; //works
a.Set_Size(5);
Square_Matrix a,b; //doesn't work as a lone statement, the above does though
头文件:
#include <iostream>
using namespace std;
class Square_Matrix
{
public:
int **matrix;
int size;
Square_Matrix();
~Square_Matrix(); //causing the problem
void Set_Size (int new_size);
}
.cpp文件:
#include <iostream>
using namespace std;
#include "Square_Matrix.h"
Square_Matrix::Square_Matrix()
{
size = 0;
}
Square_Matrix::~Square_Matrix() //causing the problem
{
for (int i = 0; i < size; i++){
delete [] matrix[i];
}
delete [] matrix;
}
答案 0 :(得分:2)
您的默认构造函数不初始化数据成员矩阵。所以你的程序有不确定的行为。
您可以通过以下方式定义析构函数和构造函数
Square_Matrix::Square_Matrix()
{
size = 0;
matrix = nullptr;
}
或者
Square_Matrix::Square_Matrix() : matrix( nullptr ), size( 0 )
{
}
Square_Matrix::~Square_Matrix() //causing the problem
{
if ( matrix )
{
for (int i = 0; i < size; i++){
delete [] matrix[i];
}
delete [] matrix;
}
}
还要考虑到您需要定义复制构造函数和复制赋值运算符,或者禁止复制和分配类的对象。