C++ MatrixMultiply

 #include <iostream>
#include <iterator>
using namespace std;
enum value:int{ MAXVALUE=1000000 };
template<typename T, unsigned int N=2, unsigned int M=3>
class Matrix{
 private:
  T** A;
  int k=1;
  public:
   Matrix(const T (&array)[N][M]);
   Matrix(const Matrix& copy); //拷贝构造函数. 
   ~Matrix();
   int rows()const; //数组的行数. 
   int clowns()const; //数组的列数. 
   T* const operator[](const int& index); //T* const 表明指针指向的地址为const的. 
};
template<typename T, unsigned int N, unsigned int M>
Matrix<T, N, M>::Matrix(const T (&array)[N][M])
{
 this->A=new int* [N]; //动态分配一个二维数组. 
 for(int i=0; i<N; ++i){
  A[i]=new int[M];
 }
 
 
 for(int x=0; x<N; ++x){//拷贝初始化二维数组. 
  for(int y=0; y<M; ++y){
   A[x][y]=array[x][y];
  }
 }
 cout<<"success to create"<<endl;
}
template<typename T, unsigned int N, unsigned int M>
Matrix<T, N, M>::Matrix(const Matrix<T, N, M>& copy)
               :A(copy.A)
{
 cout<<"copy for creating"<<endl;
}
template<typename T, unsigned int N, unsigned int M>
Matrix<T, N, M>::~Matrix()
{
 if(A != nullptr){
  delete[] A;
 }
 cout<<"destroy array"<<endl;
}
template<typename T, unsigned int N, unsigned int M>
int Matrix<T, N, M>::rows()const
{
 return M;
}
template<typename T, unsigned int N, unsigned int M>
int Matrix<T, N, M>::clowns()const
{
 return N;
}
template<typename T, unsigned int N, unsigned int M>
T* const Matrix<T, N, M>::operator[](const int& index)
{
 return A[index];
}
template<typename T, unsigned int N, unsigned int M, unsigned int X, unsigned int Y>
void matrixMultiply(Matrix<T, N, M>& A, Matrix<T, X, Y>& B)
{
 int ARow=A.rows();
 int BClown=B.rows();
 int AClown=A.clowns();
 T t[ARow][BClown];
 ostream_iterator<T> os(cout, "   ");
 
 if(A.clowns() != B.rows()){
  cout<<"incompatible"<<endl;
  
 }else{
  for(int i=0; i<ARow; ++i){//矩阵A*B获得一个:例如 A(30*50) B(50*40)获得的矩阵为 30*40;
   for(int j=0; j<BClown; ++j){
    t[i][j]==0;
    
    for(int k=0; k<AClown; ++k){
     //T a=A[i][k];
     //T b=B[k][j];
     t[i][j] += A[i][k] * B[k][j];//把A的clowns做为B的rows
    }
   }
  }
 }
 
 for(int i=0; i<ARow; ++i){
  for(int j=0; j<BClown; ++j){
   cout<<t[i][j]<<endl;
  }
 }
}
int main()
{
 int A[2][3]={{1, 2, 3}, {4, 5, 6}};
 int B[2][3]={{7,8,9}, {10, 11, 12}};
 Matrix<int> m1(A);
 Matrix<int> m2(B);
 matrixMultiply(m1, m2);
 //const int* const ptr=0;
 return 0;
}

转载于:https://my.oschina.net/SHIHUAMarryMe/blog/540489

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值