求大神帮忙看看C++矩阵乘法 下边是我的程序 以及运行后出现的问题
#include<iostream>#include<ctime>#include<cmath>usingnamespacestd;classmatrix{private...
#include <iostream>
#include <ctime>
#include <cmath>
using namespace std;
class matrix
{private:
int mat[4][4];
public:
void input();
void display();
matrix operator * (matrix &a,matrix &b);
};
void matrix::input()
{ for (int i=0;i<4;i++)
for (int j=0;j<4;j++)
cin>>mat[i][j];
}
void matrix::display()
{for (int i=0;i<4;i++)
{ for (int j=0;j<4;j++)
cout<<mat[i][j]<<" ";
cout<<endl;
}
}
matrix operator * (matrix &a,matrix &b)
{matrix c;
for (int i=0;i<4;i++)
{ for (int j=0;j<4;j++)
for(int k=0;k<4;k++)
c.mat[i][j]+=a.mat[i][k]*b.mat[k][j];
}
return c;
}
int main()
{
matrix a;
cout<<"shuru:"<<endl;
a.input();
cout<<"a wei:"<<endl;
a.display();
return 0;
}
出现的问题:
error C2804: binary 'operator *' has too many parameters
1.cpp(38) : error C2248: 'mat' : cannot access private member declared in class 'matrix'
1.cpp(8) : see declaration of 'mat'
cpp(38) : error C2248: 'mat' : cannot access private member declared in class 'matrix'
1.cpp(8) : see declaration of 'mat'
1.cpp(38) : error C2248: 'mat' : cannot access private member declared in class 'matrix'
1.cpp(8) : see declaration of 'mat'
Error executing cl.exe.
貌似就是矩阵乘法的定义有问题 展开
#include <ctime>
#include <cmath>
using namespace std;
class matrix
{private:
int mat[4][4];
public:
void input();
void display();
matrix operator * (matrix &a,matrix &b);
};
void matrix::input()
{ for (int i=0;i<4;i++)
for (int j=0;j<4;j++)
cin>>mat[i][j];
}
void matrix::display()
{for (int i=0;i<4;i++)
{ for (int j=0;j<4;j++)
cout<<mat[i][j]<<" ";
cout<<endl;
}
}
matrix operator * (matrix &a,matrix &b)
{matrix c;
for (int i=0;i<4;i++)
{ for (int j=0;j<4;j++)
for(int k=0;k<4;k++)
c.mat[i][j]+=a.mat[i][k]*b.mat[k][j];
}
return c;
}
int main()
{
matrix a;
cout<<"shuru:"<<endl;
a.input();
cout<<"a wei:"<<endl;
a.display();
return 0;
}
出现的问题:
error C2804: binary 'operator *' has too many parameters
1.cpp(38) : error C2248: 'mat' : cannot access private member declared in class 'matrix'
1.cpp(8) : see declaration of 'mat'
cpp(38) : error C2248: 'mat' : cannot access private member declared in class 'matrix'
1.cpp(8) : see declaration of 'mat'
1.cpp(38) : error C2248: 'mat' : cannot access private member declared in class 'matrix'
1.cpp(8) : see declaration of 'mat'
Error executing cl.exe.
貌似就是矩阵乘法的定义有问题 展开
2个回答
展开全部
重载的*运算符,是针对对象的,也就是说c = a*b,其中a是你的对象,b才是参数,所以改成
matrix operator*(matrix &b),然后函数内的所有a.mat改成mat
下面是我很早以前写的 (有点弱的代码。。):
Matrix<T> operator*(const Matrix<T> obj)
{
Matrix<T> tmp(rows, obj.cols);
mul(obj, tmp);
return tmp;
}
Matrix<T> mul(const Matrix<T> obj, Matrix<T> &result)
{
if(obj.rows != cols || !rows || !cols || !obj.rows || !obj.cols)
notMatch(result);
result.resize(rows, obj.cols);
for(int i = 0;i < rows;i++)
for(int j = 0;j < obj.cols;j++)
for(int k = 0;k < cols;k++)
result.mat[i][j] += mat[i][k]*obj.mat[k][j];
return result;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询