本帖最后由 Croper 于 2019-4-3 00:33 编辑
写了个矩阵的类,实现了矩阵乘法,你可以参考下
方向可能有点小问题,毕竟这一块都快忘光了。。。
#include <initializer_list>
#include <iostream>
template <int _cy, int _cx> class Matrix {
int _data[_cy][_cx];
public:
int* operator[](int rowindex) {
return _data[rowindex];
}
const int* operator[](int rowindex) const {
return const_cast<Matrix*>(this)->operator[](rowindex);
}
Matrix() {
memset(_data, 0, sizeof(_data));
}
Matrix(const std::initializer_list<int>& list) :Matrix() {
int *p = (int*)_data;
for (auto it = list.begin(); it != list.end(); ++it, ++p) {
*p = *it;
}
}
Matrix(const Matrix& m2) {
memcpy(_data, m2._data, sizeof(_data));
}
template <int _cz>
Matrix<_cy, _cz> operator*(const Matrix<_cx, _cz>& m2) {
Matrix<_cy, _cz> ret;
for (int y = 0; y < _cy; ++y) for (int z = 0; z < _cz; ++z) {
for (int x = 0; x < _cx; ++x) {
ret[y][z] += _data[y][x] * m2[x][z];
}
}
return ret;
}
void print() {
std::cout << std::endl;
for (int y = 0; y < _cy; ++y) {
for (int x = 0; x < _cx; ++x) {
std::cout << '\t' << _data[y][x];
}
std::cout << std::endl;
}
}
};
int main() {
Matrix<2,3> m1 = { 1,2,3,4,5,6 };
Matrix<3, 4> m2 = { 1,2,3,4,5,6,7,8,9,10,11,12 };
m1.print();
m2.print();
auto m3 = m1 * m2;
m3.print();
system("pause");
}
|