我有 2 个代表矩阵的类:
1. RegularMatrix - 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;
}
关于c++ - 2 个不同对象的交换运算符重载 +,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3764604/