2つの異なるオブジェクトの通勤オペレーターの過負荷 +
-
04-10-2019 - |
質問
マトリックスを表す2つのクラスがあります。
1.レギュラーマトリックス-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