首页 > 解决方案 > 动态分配“向量”类的数组

问题描述

所以我必须实现一个'Matrix'抽象类,它使用指向'Vector'的指针数组作为其内容。
'Square_matrix' 是 Matrix 的实际实现。

class Vector
{
    int dim;  // dimension
    int* a;   // actual array
public:
    Vector(int n)
    {
        dim = n;
        a = new int[n];
    }

};

class Matrix     //it will be an abstract class
{
protected:
    Vector* v;
public:
    Matrix(int col, int lin)
    {
        //here is my problem
    }
};

class Square_matrix : public Matrix
{
    int dim;
public:
    Square_matrix(int dim) 
        : Matrix(dim, dim) { this-> dim = dim; }
};

我怎样才能使这样的工作?

Matrix(int lin, int col)
{
   v = new (Vector*)[lin];
   for(int i = 0; i < lin; i++)
   {
       v[i] = new Vector(col);
   }
}

标签: c++oop

解决方案


当然使用std::vector<std::vector<int>>可能不是你想做的;D。

关于代码中的问题 --- 你在 Vector 中保留整数:

int* a; // int a[];

并且您将向量保留在矩阵中

Vector* v; // Vector v[]

但是在您的构造函数中,您每次都尝试分配新向量,因此为了保持一致,您实际上应该在 v 的声明中添加一颗星:

Vector** v; // Vector* v[];
...
Matrix(int lin, int col)
{
   v = new Vector*[lin];
   for(int i = 0; i < lin; i++)
   {
       v[i] = new Vector(col);
   }
}

或者,您可以使用更复杂的解决方案,保持 v 的声明,因为它现在在那里,并使用placement new:

Vector* v; // Vector v[]
...
Matrix(int col, int lin) // what if somebody mixes order of col and lin?
{
        // watch out for alignment if you do such tricks!!!
        v = reinterpret_cast<Vector*>(new char[sizeof(Vector)*lin]);
        for(int i = 0; i < lin; i++)
        {
                new (v+i) Vector(col);
        }
}

当然,不要忘记析构函数、异常安全等等……


推荐阅读