简体   繁体   English

矩阵 class 模板,不同类型矩阵的乘法或加法

[英]matrix class template,the multiplication or addition of different types of matrices

I am writing a matrix class template.我正在写一个矩阵 class 模板。 I want to implement the multiplication or addition of different types of matrices( for example, between real and imaginary matrices ), but I cannot access the data members of another type of matrix.我想实现不同类型矩阵的乘法或加法(例如,实数和虚数矩阵之间),但我无法访问其他类型矩阵的数据成员。 How should I solve this problem?我应该如何解决这个问题?

template <class Type>
class Matrix
{
    Type** p_data; //Represents matrix data
    int row, col; //Represents the number of rows and columns of the matrix
public:
    Matrix(int r, int c);
    ~Matrix(); 
    Matrix(Type *data, int row, int col);
    Type* operator[] (int i); 
    // Overload [], for Matrix object M, can be accessed by M [I] [J] to 
    // access the i + 1 line, the J + 1 column element
    Matrix &operator = (const Matrix& m); 
    // Overload =, implement matrix overall assignment, if the row / column does not wait, 
    // return space and reassign
    bool operator == (const Matrix& m) const; //Overload ==, determined whether the matrix is ​​equal
    template <class Type1>
    Matrix operator + (const Matrix<Type1>& m) const;
    // Overload +, complete matrix addition, can assume 
    // that the two matrices meet the addition conditions (the rows, the columns are equal)
    template <class Type1>
    Matrix operator * (const Matrix<Type>& m) const; 
    // Overload *, complete matrix multiplication, can assume that two matrices meet multiplication 
    // conditions (this.col = m.row)
    template <class Type1>
    friend std::ostream& operator << (std::ostream& out,Matrix<Type1>& c);
};
template<class Type>
template <class Type1>
Matrix<Type> Matrix<Type>::operator + (const Matrix<Type1>& m) const{
    Matrix<Type> res(row,col);
    for(int i=0;i<row;++i)
        for(int j=0;j<col;++j)
            res.p_data[i][j] =p_data[i][j] + m.p_data[i][j];  //  error in this line
    return res;
}

You can use a friend declaration您可以使用朋友声明

template <typename T>
class Matrix
{
  template <typename U>
  friend class Matrix;

  // ...
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM