- 论坛徽章:
- 1
|
我是这么写的, 但是有几个问题:
matrix.h:
- #ifndef MATRIX_H__
- #define MATRIX_H__
- #include <iostream>
- template <class Numeric, int rows, int cols>
- class Matrix {
- public:
- Numeric elements[rows][cols];
- Matrix(Numeric arr[rows][cols]) {
- for (int i = 0; i < rows; ++i) {
- for (int j = 0; j < cols; ++j) {
- elements[i][j] = arr[i][j];
- }
- }
- }
- template <int cols2>
- const Matrix<Numeric, rows, cols2>&
- operator*(Matrix<Numeric, cols, cols2>& m) {
- Numeric arr[rows][cols2];
- for (int i = 0; i < rows; ++i) {
- for (int j = 0; j < cols2; ++j) {
- Numeric sum = 0;
- for (int k = 0; k < cols; ++k) {
- sum += elements[i][k] * m.elements[k][j];
- }
- arr[i][j] = sum;
- }
- }
- return Matrix<Numeric, rows, cols2>(arr);
- }
- void dump() {
- for (int i = 0; i < rows; ++i) {
- for (int j = 0; j < cols; ++j) {
- std::cout << elements[i][j] << ' ';
- }
- std::cout << std::endl;
- }
- }
- };
- #endif
复制代码
test.cpp
- #include "matrix.h"
- #include <iostream>
- using namespace std;
- int main() {
- int arr[2][3] = {{1,2,3},{4,5,6}};
- int arr2[3][2] = {{1,2},{3,4},{5,6}};
- Matrix<int, 2, 3> m1(arr);
- Matrix<int, 3, 2> m2(arr2);
- m1.dump();
- m2.dump();
- Matrix<int, 2, 2> m3 = m1 * m2;
- m3.dump();
- }
复制代码
1. 如果我把elements这个成员声明成private的话, 代码编译不过去。
2. return Matrix<Numeric, rows, cols2>(arr); 这一行会报warning:
matrix.h:31: warning: returning reference to temporary
为什么? 怎么修改? |
|