您的位置:首页 > 编程语言 > C语言/C++

C++ MatrixMultiply

2015-12-07 00:00 387 查看
#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)
[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)
[M])
{
this->A=new int*
; //动态分配一个二维数组.
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: