模板类型矩阵类添加:正确添加中的错误

时间:2019-02-18 03:18:01

标签: c++11

任何人都可以帮助我找出为什么我的矩阵总和不是应该的样子吗?

template <typename T>
Matrix<T> Matrix<T>::operator + (const Matrix<T> &M){
    Matrix<T> tmp(m,n,M.x); 
    for(int i=0;i<m;i++)
        for(int j=0;j<n;j++)
            tmp.Mat[i][j]+= Mat[i][j]+ M.Mat[i][j];
    return tmp; 
}

这是我程序的主体:

#include <iostream>
#include <vector>

template <typename T>
class Matrix {
private:
    unsigned int m; unsigned int n;
    std::vector<T> x;
    std::vector<T> y;
    std::vector<std::vector<int>> Mat;


public:
    Matrix (unsigned int m, unsigned int n, std::vector<T> x);
    Matrix (const Matrix<T> &M); //= default;
   // Matrix ();
    Matrix<T> operator = (const Matrix<T> &M);      // Assignment
    Matrix<T> operator + (const Matrix<T> &M);      // Addition
    Matrix<T> operator - (const Matrix<T> &M);      // Subtraction
    Matrix<T> operator * (const T &scalar);          // Scalar Multiplication
    Matrix<T> operator * (const Matrix<T> &M);      // Matrix Multiplication

    friend std::ostream& operator << (std::ostream& os, const Matrix<T> &M){

    for (int i = 0; i< M.m; i++){
        for (int j = 0; j< M.n; j++){
            os << M.Mat[i][j] << ' ';
        }
        os << '\n';
    }
    os << '\n' ;
    return os;
    }
};

template <typename T>
Matrix<T>::Matrix (unsigned int m, unsigned int n, std::vector<T> x){ //constructor
this -> m = m;
this -> n = n;
this -> x = x;

int index = 0;
Mat.resize(m);
for (unsigned int i = 0; i < Mat.size(); i++) {
    Mat[i].resize(n);
}
for (unsigned int i = 0; i<m; i++){
    for (unsigned int j = 0; j<n; j++){
        Mat[i][j] = x[index];
        index++;
    }
}
}

template<typename T>
Matrix<T>::Matrix(const Matrix &M) //copy constructor
:
m(M.m),
n(M.n),
Mat(M.Mat)
{}

这是我的主要内容: 注意:在初始化过程中,我们要求构造函数使用2个无符号整数和一个线性容器,该容器中将根据输入将元素分为行和列。

int main(){
std::vector<int> x = {1,2,3,4};
std::vector<int> y = {5,6,7,8};
std::vector<int> z = {9,10,11,12};

Matrix<int> A{2,2,x};
Matrix<int> B{2,2,y};
Matrix<int> C{2,2,z};

C = B;


std::cout << "A\n" << A;
std::cout << "B\n" << B;
std::cout << "C\n" << C;

Matrix<int> E(A + B);
std::cout << "E\n" << E;
}

当我添加A和B时,我总是得到 11 14 17 20

就像矩阵B在加到A之前加倍了

谢谢!

1 个答案:

答案 0 :(得分:0)

A.operator+(M)计算A + 2*M。您使用M的内容两次-一次构造tmpMatrix<T> tmp(m,n,M.x)),一次更新(tmp.Mat[i][j]+= Mat[i][j]+ M.Mat[i][j]