C++ の理解を深めるために、独自のマトリックス クラスを構築しています。テンプレート化されているので、int マトリックス、float、または boolean マトリックスを使用できます。動的メンバー要素を持たないため、コピー コンストラクター、代入演算子、またはデストラクターを実装するつもりはありませんでしたが、次の場合:
Matrix<float,3,4> mat1;
Matrix<int,45,45> mat2;
mat1 = mat2;
次のエラーが返されます。
/Users/Jake/Dropbox/C++/test.cpp: In function ‘bool test1()’:
/Users/Jake/Dropbox/C++/test.cpp:23: error: no match for ‘operator=’ in ‘m2 = m1’
/Users/Jake/Dropbox/C++/Matrix.h:22: note: candidates are: Matrix<float, 3u, 4u>& Matrix<float, 3u, 4u>::operator=(const Matrix<float, 3u, 4u>&)
2 つの行列が両方とも float または両方とも int であれば問題ありません。寸法が一致している必要はありません。したがって、型が異なる場合を除き、デフォルトの代入演算子はうまく機能します。そこで、独自の代入演算子を実装します。
template <class T, unsigned int rows, unsigned int cols>
template <class T2, unsigned int rows2, unsigned int cols2>
Matrix<T, rows2, cols2> & Matrix<T,rows,cols>::operator= (const Matrix<T2, rows2, cols2> & second_matrix){
unsigned int i,j;
for (i=0; i < rows2; i++){
for (j=0; j < cols2; j++){
data[i][j] = second_matrix(i,j);
}
}
this->_rows = rows2;
this->_cols = cols2;
return *this;
}
これは、タイプが異なるが同じ次元である場合に機能しますが、2 番目の値は 2 番目のタイプから 1 番目のタイプに変換されます。私の質問は、それらが異なるタイプと異なる次元になるように設定するにはどうすればよいですか?そして、これを2番目または2番目のコピーを指すように設定するだけです?