Ich versuche, einen Konstruktor, Destruktor und Kopie Konstruktor für eine Matrix-Klasse zu erstellen, und ich bin nicht so sicher, ob ich es gut mache.die Art des Schreibens Konstruktor, Dekonstruktor und Kopie Konstruktor für Matrix-Klasse
Insbesondere bin ich über 2 Dinge nicht sicher:
Ist der destructor des freien Speichers nehme auch für den Speicher, der in dem Kopie-Konstruktor zugeordnet ist?
Was die Zeile
Mat[i][j]=other[i][j]
betrifft (siehe unten stehenden Code), frage ich mich, ob ich stattdessen schreiben sollte?
class Matrix
{
private:
int rows;
int cols;
int **Mat;
public:
Matrix (const int &rows,const int &cols);
Matrix (const Matrix &other);
~Matrix();
};
Matrix::Matrix(const int &n_rows,const int &n_cols) //constructor of class Matrix
{
rows=n_rows;
cols=n_cols;
Mat=new int* [cols];
for(int i =0;i<rows;i++)
Mat[i]=new int[cols];
for(int i=0;i<rows;i++)
for(int j=0;j<cols;j++)
Mat[i][j]=0;
}
Matrix::~Matrix() //destructor
{
for(int i =0;i<rows;i++)
delete Mat[i];
delete[] Mat;
}
Matrix::Matrix(const Matrix &other) //copy constructor
{
cols=other.cols;
rows=other.rows;
Mat=new int* [other.rows];
for(int i =0;i<other.rows;i++)
Mat[i]=new int[other.cols];
for(int i=0;i<other.rows;i++)
for(int j=0;j<other.cols;j++)
Mat[i][j]=other[i][j];
}
Sie wollen auch den Kopierzuweisungsoperator. Siehe [Regel von 3/5/0] (http://en.cppreference.com/w/cpp/language/rule_of_three). –
Verwenden Sie einen Std :: Vektor. –
Ich glaube Francois ging in diese Richtung, aber ich könnte falsch liegen. Um eine tiefe Kopie zu erstellen, müssen Sie den Operator "assignment =" überladen. Ohne eine tiefe Kopie haben Sie eine flache Kopie, die der Destruktor den gesamten mit dieser Instanz assoziierten Speicher freigibt. –