C++ &引用;在抛出';std::bad#u alloc';what():std::bad“u alloc”;但奇怪的是,我有很多可用的内存

C++ &引用;在抛出';std::bad#u alloc';what():std::bad“u alloc”;但奇怪的是,我有很多可用的内存,c++,pointers,runtime-error,delete-operator,C++,Pointers,Runtime Error,Delete Operator,我写了一个类,然后用它创建了另一个类,并在测试程序中使用了这两个类。我的第二个类使用动态分配,所以我按照建议创建了三个大类:创建者、副本创建者和析构函数。但是当我尝试使用class-friend操作符时,程序停止并返回上面的消息。让我展示一些代码: class matrix { public: int n; complex **M; matrix(int dim); //construtor matrix(int dim, double a);//construt

我写了一个类,然后用它创建了另一个类,并在测试程序中使用了这两个类。我的第二个类使用动态分配,所以我按照建议创建了三个大类:创建者、副本创建者和析构函数。但是当我尝试使用class-friend操作符时,程序停止并返回上面的消息。让我展示一些代码:

class matrix
{
public:
    int n;
    complex **M;
    matrix(int dim); //construtor
    matrix(int dim, double a);//construtor
    matrix(const matrix &obj);//construtor de copia (necessario para passar objetos para funções)
    ~matrix(); //destrutor
    friend matrix operator *(matrix a, matrix b);
};

matrix::matrix(int dim) 
{
    int i = 0;
    n = dim;
    M = new complex*[dim];
    cout << "criando objeto \n";

    for(i=0;i<n;i++)
    {
        M[i] = new complex [dim];
    }
}

matrix::matrix(int dim, double a) 
{
    int i = 0, j = 0; 
    n = dim;
    M = new complex*[dim];
    cout << "criando objeto \n";

    for(i=0;i<n;i++)
    {
        M[i] = new complex [dim];
    }

    for(i=0;i <dim; i++){
        for(j=0; j<dim; j++){
            M[i][j] = complex(a,0);     
        }
    }
}

matrix::matrix(const matrix &obj)
{
    int i = 0, j = 0;
    M = new complex*[n];
    cout << "criando copia de objeto \n";

    for(i=0;i<n;i++)
    {
        M[i] = new complex [n];
    }

    for(i=0;i <n; i++){
        for(j=0; j<n; j++){
            M[i][j] = obj.M[i][j];      
        }
    }
    n = obj.n;
}

matrix::~matrix()
{
    int i;
    cout << "destruindo obejto \n";
    for(i=0;i<n;i++)
        delete [] M[i];
    delete M;
}

matrix operator *(matrix a, matrix b)
{
    int i,j,k;
    matrix mult(a.n, 0);
    bool dim;
    if(a.n == b.n) dim = true;
    else dim = false;
    if(dim == true) 
    {   
        for(i=0; i < a.n; i++){ 
            for(j=0; j < a.n; j++){
                for(k=0; k < a.n; k++){ 
                    mult.M[i][j] = mult.M[i][j] + a.M[i][k]*b.M[k][j];
                }
            }
        }
        return mult;
    }
    else return zeros(a.n);
}
类矩阵
{
公众:
int n;
复杂**M;
矩阵(int dim);//构造函数
矩阵(int dim,双a);//construtor
矩阵(const matrix&obj);//副本的构造(必要的部分)
~matrix();//析构函数
友元矩阵算子*(矩阵a,矩阵b);
};
矩阵::矩阵(int-dim)
{
int i=0;
n=昏暗;
M=新复合体*[dim];

复制构造函数是否有未定义的行为:
M=new complex*[n];
,但是分配
n
的时间要晚得多。顺便说一句,这是实现
n*n
矩阵的一种不好的方法。您在您的构造函数中进行了多次分配。如果稍后的分配抛出,则早期的分配会泄漏。此外,
运算符*
应该按常量ref而不是按值获取其参数,并且应该是imp根据
运算符*=
实现。非常感谢!它确实解决了主要问题,但我现在仍然收到一个分段错误。有什么想法吗?“运算符*应该根据常量ref而不是值“why is that?”获取其参数,并且应该真正根据运算符*=”实现为了避免与指针一元运算符*的误解?