运算符重载:"operator+"必须采用零个或一个参数

operator over loading: "operator+"must take either zero or one argument

我有一个名为 IntMatrix

的矩阵 class
namespace mtm
{
    class IntMatrix
    {
    private:
        int** data;
        int col;
        int row;
    public:
          IntMatrix(int row,int col,int num=0);
         IntMatrix(const IntMatrix& mat);
          //some functions
          IntMatrix ::operator+(int num) const;
          friend IntMatrix operator+(const int &num, const IntMatrix& matrix);
};
//ctor
IntMatrix::IntMatrix(int row,int col, int num) :data(new int*[row]), col(col), row(row)
    {
        for (int i = 0; i < col; i++)
        {
            data[i] = new int[col];
        }
        for (int i = 0; i < row; i++)
        {
            for (int j = 0; j < col); j++)
            {
                data[i][j] = num;
            }
        }
    }
}

我正在尝试重载 operator+,这样它就可以工作了:

//copy ctor
IntMatrix::IntMatrix(const IntMatrix& mat)
{
    data=new int*[mat.row];
    for(int i = 0; i < mat.row; i++) 
    {
        data[i]=new int[mat.col];
    }
    row=mat.row;
    col=mat.col;
    for(int i=0;i<row;i++)
    {
     for(int j=0;j<col;j++)
     {
         data[i][j]=mat.data[i][j];
     }
    }
}

IntMatrix IntMatrix::operator+(int num) const
{
    IntMatrix new_Matrix(*this);
    for(int i=0;i<new_Matrix.row;i++)
    {
        for(int j=0;j<new_Matrix.col;j++)
        {
            new_Matrix.data[i][j]+=num;
        }
    }
    return new_Matrix;
}
// the function I have problem with:
IntMatrix IntMatrix::operator+(const int &num, const IntMatrix& matrix) 
{
    return matrix+num;
}

int main()
{
 mtm::IntMatrix mat(2,1,3);
 mtm::IntMatrix mat2=2+mat;
return 0;
}

无论我做什么,我总是收到这个错误: 错误:‘mtm::IntMatrix mtm::IntMatrix::operator+(const int&, const mtm::IntMatrix&)’必须采用零或一个参数 IntMatrix IntMatrix::operator+(const int &num, const IntMatrix& 矩阵)

我试过了:

friend IntMatrix operator+(const int &num, const IntMatrix& matrix);
IntMatrix operator+(const int &num, const IntMatrix& matrix);
IntMatrix operator+(const int &num, const IntMatrix& matrix)const;
IntMatrix operator+(int &num, const IntMatrix& matrix);
IntMatrix operator+( int num, const IntMatrix& matrix);

但是我所有的错误都一样,所以有人知道正确的写法是什么吗?

我不知道你定义了什么来向矩阵添加自动标量,但想象一下类似

的东西
IntMatrix IntMatrix::operator+(int k) const
{    
    IntMatrix temp(this->x+k, this->y+k, this->z+k);
    return temp;
}

所以有一个向量 foo [0,1,2] 你可以这样做:

IntMatrix r = foo + 2; 

并且 r 将是 [2,3,4]

friend 声明函数 而不是 使其成为 class 的一部分。 int+IntMatrix 运算符是 not IntMatrix::operator+ - 它只是 operator+.

//        wrong - delete this part
//        vvvvvvvvvvv
IntMatrix IntMatrix::operator+(const int &num, const IntMatrix& matrix) 
{
    return matrix+num;
}