提问者:小点点

防止两个方法共享相同的代码?


IntMatrix类的。cpp文件中,我编写了以下代码:

IntMatrix& IntMatrix::operator+=(int num) {
    int matrix_size=size();
    for (int i=0;i<matrix_size;i++)
    {
        data[i]+=num;
    }
    return *this;
}

IntMatrix operator+(const IntMatrix &matrix, int scalar) {
    IntMatrix result=matrix;
    result+=scalar;
    return result;
}

IntMatrix operator+(int scalar, const IntMatrix &matrix) {
    IntMatrix result=matrix;
    result+=scalar;
    return result;
}

正如您所看到的,两个operator+函数具有完全相同的代码,如何防止这种情况并限制代码重复呢? (我可以用一个呼叫另一个吗)

注意:我使用的是C++11

在实现了建议的解决方案(经过一些编辑)之后,现在我有了:

。h文件:

IntMatrix operator+(const IntMatrix &matrix, int scalar);

IntMatrix operator+(int scalar, const IntMatrix &matrix);

。cpp文件:

IntMatrix operator+(const IntMatrix &matrix, int scalar){
    IntMatrix out=matrix;
    out += scalar;
    return out;
}

IntMatrix operator+(int scalar, const IntMatrix &matrix) {
    return matrix + scalar;
}

共2个答案

匿名用户

是的,您只需调用运算符+,顺序颠倒即可:

IntMatrix operator+(int scalar, const IntMatrix &matrix) {
  return matrix + scalar;  // calls operator+(const IntMatrix &matrix, int scalar) 
}

另外,对于将IntMatrix作为第一个参数的operator+,您可以按值获取参数,因为您无论如何都是在制作IntMatrix的副本:

IntMatrix operator+(IntMatrix matrix, int scalar) {
    matrix += scalar;
    return matrix;
}

匿名用户

您可以避免一个间接性,并以运算符+=的方式实现运算符+,而不会出现代码重复:

IntMatrix operator+(IntMatrix matrix, int scalar);

IntMatrix operator+(int scalar, IntMatrix matrix);

IntMatrix operator+(IntMatrix matrix, int scalar) {
    return matrix+=scalar;
}

IntMatrix operator+(int scalar, IntMatrix matrix) {
    return matrix+=scalar;
}