交换操作员超载 + 2个不同对象的
-
04-10-2019 - |
题
我有两个代表矩阵的类:
1.常规amatrix -o(n^2)表示
2. Sparsematrix-表示为链接列表(无零)的矩阵。
可以说我有:
RegularMatrix a;
SparseMatrix b;
我希望能够做:
a+b;
并且:
b+a;
因此,我要超载 +运算符。我的问题是,由于我希望增加交换性(A+B = B+A),所以我是否需要实现2个过载,每种情况一个?
RegularMatrix operator+(const RegualarMatrix &, const SparseMatrix &);
RegularMatrix operator+(const SparseMatrix & ,const RegualarMatrix &);
还是编译器本身决定的一般形式?
谢谢
解决方案
是的,您需要两个版本。但是,如果操作确实是可交换的,则可以将一个转发给另一个
RegularMatrix operator+(const SparseMatrix &a, const RegualarMatrix &b) {
return b + a;
}
其他提示
这两个版本都是必需的,只需在首次过载之后写:
RegularMatrix operator+(const SparseMatrix &a, const RegualarMatrix &b)
{
return operator+(b,a);
}
或更简单的版本:
RegularMatrix operator+(const SparseMatrix &a, const RegualarMatrix &b)
{
return b + a;
}
不隶属于 StackOverflow