C++;2个矩阵的加法和乘法程序 我在C++中编写了这个代码,用运算符重载来增加和增加2个矩阵。当我执行代码时,它在第57行和第59行生成错误,这是非法的结构操作(这两行上的错误相同)。请解释我的错误。提前感谢:) 类矩阵{ 公众: int i,j,row,col,mat[10][10]; 无效输入(); 矩阵算子+(矩阵mm2); 矩阵算子*(矩阵mm2); 无效输出(); }; void矩阵::输入(){ coutrow>>col; cout

C++;2个矩阵的加法和乘法程序 我在C++中编写了这个代码,用运算符重载来增加和增加2个矩阵。当我执行代码时,它在第57行和第59行生成错误,这是非法的结构操作(这两行上的错误相同)。请解释我的错误。提前感谢:) 类矩阵{ 公众: int i,j,row,col,mat[10][10]; 无效输入(); 矩阵算子+(矩阵mm2); 矩阵算子*(矩阵mm2); 无效输出(); }; void矩阵::输入(){ coutrow>>col; cout,c++,matrix,C++,Matrix,output()是一个函数,您不能将它直接放在cout流上。只需在单独的行中调用它 改变 cout<<"\nSum is "<<m3.output(); ... cout<<"\nProduct is "<<m3.output(); cout常见错误: matrix matrix::operator+(matrix mm2)应该是matrix matrix::operator+(const matrix&mm2){。此外,由于没有复制构造函数,这

output()是一个函数,您不能将它直接放在cout流上。只需在单独的行中调用它

改变

cout<<"\nSum is "<<m3.output();
...
cout<<"\nProduct is "<<m3.output();
cout常见错误:

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;
}
//声明为好友
模板CMatrix运算符+(常数CMatrix&a、常数CMatrix&b)
{
无符号整数a_行=a.m_行;无符号整数a_列=a.m_列;
无符号整数b_行=b.m_行;无符号整数b_列=b.m_列;
如果(a_行!=b_行| a_列!=b_列)抛出“尺寸不一致”;
CMatrix加法(a列,b列);
温度T=0;

对于(unsigned int i=0;我请突出显示这些行,然后再进行一次bash a缩进。您介意分别标记哪些行是57和59吗?请您记下哪些行是57和59,因为这不是您的完整文件。您在命令行中输入了多少行和列?@rippy-为什么不编辑该问题并标记它们?@m吃…就像一个符咒:)
cout<<"\nSum is ";
m3.output();
...
cout<<"\nProduct is ";
m3.output();
cout<<"\nSum is "<<m3;
...
cout<<"\nProduct is "<<m3;
//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;
}