言語の理解を深めるために、C++で独自の行列クラスを実装しています。 + +演算子を使用している場合は、+演算子で使用することをお勧めします。C++演算子+演算子+ =オーバーロード
template <class T>
const Matrix<T>& Matrix<T>::operator+=(const Matrix<T> & second_matrix){
//Learn how to throw errors....
if (rows != second_matrix.getNumRows() || cols != second_matrix.getNumCols()){throw "Dimension mismatch.";}
int i,j;
for (i = 0; i < rows; i++){
for (j = 0; j < cols; j++){
data[i][j] += second_matrix.get(i,j);
}
}
return *this;
}
私は、A + = B、例えば(+ =罰金を使用することができ、エラーを返しません:
template <class T>
const Matrix<T>& Matrix<T>::operator+(const Matrix<T> &R){
Matrix<T> copy(*this);
return copy += R;
}
そしてここでは、+ =演算子のオーバーロードです:だから、それは私が持っているものです)。しかし、+演算子を呼び出す(例えば、A = B + Cは;)を返します:私は数年のためのC++を使用してきた
template <class T>
Matrix<T>::~Matrix(){
for (int i = 1; i < rows; i++){
delete[] data[i]; }
delete[] data;
}
:
ただ完全を期すために、ここに私のデストラクタですtest.cpp.out(77055) malloc: *** error for object 0x300000004: pointer being freed was not allocated
そして時にはポインタを追跡している時にも問題があります。私はそれが正常であることを願っています... 助けが素晴らしいでしょう。ありがとう!
編集:私のコピーコンストラクタです。データ配列を解放するように設定されていましたが、削除しました。今私はセグメンテーションフォールトを得る。それは操作の結果を保持している新しい(ローカルに宣言された)インスタンスであるよう
template <class T>
Matrix<T>::Matrix(const Matrix<T>& second_matrix){
rows = second_matrix.getNumRows();
cols = second_matrix.getNumCols();
data = new T*[rows];
int i,j;
for (i = 0; i < rows; i++){
data[i] = new T[cols];
}
for (i = 0; i < rows; i++){
for (j = 0; j < cols; j++){
data[i][j] = second_matrix.get(i,j);
}
}
}
コピーコンストラクタの外観は?エラーがメモリが2回解放されていることを示しているので、おそらくあなたの問題です。 –
@ Walt W:これはBig Threeの問題だと思う。 –
@Fred:大きな3つの問題は何ですか? – jakev