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

  • 本文关键字:添加 错误 类型 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 << "An" << A;
std::cout << "Bn" << B;
std::cout << "Cn" << C;
Matrix<int> E(A + B);
std::cout << "En" << E;
}

当我添加A和B时,我总是会得到11 1417 20

就像矩阵B倍增,然后添加到

预先感谢!

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]

最新更新