Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have 2 classes which represent a matrix:
1. RegularMatrix - O(n^2) representation
2. SparseMatrix - a matrix that is represented as linked list (without zeros).

lets say i have:

RegularMatrix a;
SparseMatrix b;

i want to be able to do:

a+b;

and also:

b+a;

so i'm overloading the + operator. My question is, since I want the addition to be commutative (a+b = b+a), do i need to implement 2 overloadings, one for each case?

RegularMatrix operator+(const RegualarMatrix &, const SparseMatrix &);
RegularMatrix operator+(const SparseMatrix & ,const RegualarMatrix &);

or is there a general form which the compiler decides by itself?

Thank you

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
546 views
Welcome To Ask or Share your Answers For Others

1 Answer

Yes you need both versions. But you can forward the one to the other, if the operation really is commutative

RegularMatrix operator+(const SparseMatrix &a, const RegualarMatrix &b) {
    return b + a;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...