【问题标题】:Prevent two methods to share the same code?防止两种方法共享相同的代码?
【发布时间】:2020-10-02 08:10:54
【问题描述】:
在 IntMatrix 类的 .cpp 文件中,我编写了以下代码:
IntMatrix& IntMatrix::operator+=(int num) {
int matrix_size=size();
for (int i=0;i<matrix_size;i++)
{
data[i]+=num;
}
return *this;
}
正如您所见,operator+ 两个函数的代码完全相同,我该如何防止这种情况并限制代码重复? (我可以用一个打电话给另一个)
注意:我正在使用 C++11
【问题讨论】:
标签:
c++
function
class
c++11
methods
【解决方案1】:
是的,您只需拨打operator+ 翻转订单即可:
IntMatrix operator+(int scalar, const IntMatrix &matrix) {
return matrix + scalar; // calls operator+(const IntMatrix &matrix, int scalar)
}
另外,对于operator+ 将IntMatrix 作为第一个参数,您可以按值获取参数,因为无论如何您都在制作IntMatrix 的副本:
IntMatrix operator+(IntMatrix matrix, int scalar) {
matrix += scalar;
return matrix;
}
【解决方案2】:
您可以避免一种间接方式,并根据operator+= 实现operator+ 而无需重复代码:
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;
}