C++程序来添加和乘以 2 个矩阵
C++ program to add and multiply 2 matrices
我用 c++ 编写了这段代码,使用运算符重载对 2 个矩阵进行加乘。当我执行代码时,它会在第 57 行和第 59 行生成错误,非法结构操作(两行上都有相同的错误)。请解释我的错误。提前致谢:)
class matrix{
public:
int i, j, row, col, mat[10][10];
void input();
matrix operator+(matrix mm2);
matrix operator*(matrix mm2);
void output();
};
void matrix::input(){
cout<<"nEnter number of rows and columns : ";
cin>>row>>col;
cout<<"nEnter the elements : ";
for(i=0; i<row; i++){
for(j=0;j<col;j++){
cin>>mat[i][j];
}
}
}
matrix matrix::operator+(matrix mm2){
matrix temp;
temp.row=row;
temp.col=col;
for(i=0; i<temp.row; i++){
for(j=0; j<temp.col; j++){
temp.mat[i][j]=mat[i][j]+mm2.mat[i][j];
}
}
return temp;
}
matrix matrix::operator*(matrix mm2){
matrix temp;
temp.row=row;
temp.col=col;
for(i=0; i<temp.row; i++){
temp.mat[i][j]=0;
for(j=0; j<temp.col; j++){
temp.mat[i][j]+=mat[i][j]*mm2.mat[i][j];
}
}
return temp;
}
void matrix::output(){
cout<<"Matrix is : ";
for(i=0;i<row;i++){
for(j=0;j<col;j++){
cout<<mat[i][j]<<"t";
}
cout<<"n";
}
}
int main(){
matrix m1, m2, m3;
clrscr();
m1.input();
m2.input();
m3=m1+m2;
cout<<"nSum is "<<m3.output();
m3=m1*m2;
cout<<"nProduct is "<<m3.output();
getch();
return 0;
}
output() 是一个函数,你不能直接把它放在 cout 流上。只需在单独的行中调用它。
改变
cout<<"nSum is "<<m3.output();
...
cout<<"nProduct is "<<m3.output();
自
cout<<"nSum is ";
m3.output();
...
cout<<"nProduct is ";
m3.output();
或者,您可以重载矩阵类<<运算符。然后你可以做
cout<<"nSum is "<<m3;
...
cout<<"nProduct is "<<m3;
常见错误:
matrix matrix::operator+(matrix mm2)
应该是matrix matrix::operator+(const matrix& mm2){
.此外,这将导致意外行为,因为您没有复制构造函数。
这是重载运算符+的另一种方式,概念可以扩展到其他运算符:
//declared as friend
template <class T> CMatrix<T> operator+(const CMatrix<T>& a, const CMatrix<T>& b)
{
unsigned int a_row=a.m_row;unsigned int a_col=a.m_column;
unsigned int b_row=b.m_row;unsigned int b_col=b.m_column;
if(a_row!=b_row||a_col!=b_col) throw "Dimensions do not agree";
CMatrix<T> addition(a_row,b_col);
T temp=0;
for(unsigned int i = 0; i <a_row; i++ )
for(unsigned int j = 0; j < b_col; j++ )
{
T temp1=a.GetCellValue(i,j);
T temp2=b.GetCellValue(i,j);
temp=temp1+temp2;
addition.SetCellValue(i,j,temp);
}
return addition;
}
相关文章:
- 在没有管理员权限的情况下,在 c++ 中以编程方式将程序添加到启动
- 如何将我的程序添加到文件和文件夹的macOS右键单击菜单?
- 如何将信号处理程序添加为方法
- 如何向控制台应用程序添加图标
- 不知道如何向我的程序添加循环...?
- 将事件处理程序添加到C 中的按钮
- C 从内部程序代码上将应用程序添加到Linux程序上的启动中
- 将事件处理程序添加到任何控件都会导致 Visual Studio 中出错
- 如何自动将处理程序添加到全局映射
- C++程序添加逗号以延长数字
- 如何将事件处理程序添加到桌面窗口
- 向MFC应用程序添加许可保护
- 向iOS应用程序添加64位切片会导致崩溃
- 运行时向程序添加算法
- 向程序添加详细程度
- 向Win32应用程序c++添加基本文本
- 程序添加一个用户到MySQL
- 为c++控制台应用程序添加状态栏
- 向程序添加排序算法(冒泡排序)
- 向现有的MFC应用程序添加控制台