|
发表于 2021-9-8 17:57:41
|
显示全部楼层
本楼为最佳答案
 - #include <iostream>
- using namespace std;
- template <typename element> class Matrix {
- template <typename _element>
- friend Matrix<_element> &operator*(Matrix<_element> &x1,
- Matrix<_element> &x2); //就是这两条都会报警告
- template <typename _element>
- friend Matrix<_element> &operator+(Matrix<_element> &x1, Matrix<_element> &x2);
- private:
- int row;
- int column;
- element **arr;
- public:
- Matrix() {
- row = 10;
- column = 10; //这个都为10的时候执行程序会出错 自动终止退出
- arr = new element *[row];
- for(int i = 0; i < row; i++) {
- //arr[i] = new element(column);
- arr[i] = new element[column];
- for(int j = 0; j < column; j++) {
- if(i == j)
- arr[i][j] = 1;
- else
- arr[i][j] = 0;
- }
- }
- }
- Matrix(const std::initializer_list<element> &rhs, int r, int c) {
- row = r; column = c;
- arr = new element *[row];
- for(int i = 0; i < row; ++i) {
- arr[i] = new element[column];
- for(int j = 0; j < column; ++j) {
- //arr[i][j] = rhs[i * column + j]; // 奇怪,std::initializer_list 没有 operator[]
- arr[i][j] = *(rhs.begin() + (i * column + j));
- }
- }
- }
- Matrix(element a[], int r, int c) {
- row = r;
- column = c;
- arr = new element *[row];
- int cout = 0;
- for(int i = 0; i < row; i++) {
- //arr[i] = new element(column);
- arr[i] = new element[column];
- for(int j = 0; j < row; j++) {
- arr[i][j] = a[cout];
- cout++;
- }
- }
- }
- ~Matrix() {
- for(int i = 0; i < row; i++) {
- delete[] arr[i];
- }
- delete[] arr;
- }
- //int &operator()(int row, int column) { return arr[row][column]; };
- int &operator()(int row, int column) const { return arr[row][column]; };
- void print() {
- for(int i = 0; i < row; i++) {
- cout << "[ ";
- for(int j = 0; j < column; j++) {
- cout << arr[i][j] << " ";
- }
- cout << "]" << endl;
- }
- cout << endl;
- };
- };
- template <typename element>
- Matrix<element> &operator*(Matrix<element> &x1, Matrix<element> &x2) {
- Matrix<element> *result = new Matrix<element>();
- for(int i = 0; i < 4; i++) {
- int r = 0;
- for(int j = 0; j < 4; j++) {
- for(int k = 0; k < 4; k++) {
- r += x1(k, j) * x2(i, k);
- }
- result->arr[i][j] = r;
- }
- }
- return *result;
- }
- template <typename element>
- Matrix<element> &operator+(Matrix<element> &x1, Matrix<element> &x2) {
- Matrix<element> *result = new Matrix<element>();
- for(int i = 0; i < 4; i++) {
- for(int j = 0; j < 4; j++) {
- result->arr[i][j] = x1(i, j) + x2(i, j);
- }
- }
- return *result;
- }
- int main() {
- Matrix<float> x = Matrix<float>();
- x.print();
- float w[] = {1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4};
- Matrix<float> z = Matrix<float>({1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4},4,4);
- // //就是这个 不能以这个形式传入
- Matrix<float> y = Matrix<float>(w, 4, 4);
- y.print();
- }
复制代码 |
|