user13707437
user13707437

Reputation:

Fix use of overloaded operator '+' is ambiguous?

I wrote the following code using C++11 standard:

.h file:

#include "Auxiliaries.h"

    class IntMatrix {

    private:
        Dimensions dimensions;
        int *data;

    public:
        int size() const;

        IntMatrix& operator+=(int num);
    };

Bit I am getting and error saying that:

error: use of overloaded operator '+' is ambiguous (with operand types 'const mtm::IntMatrix' and 'int') return matrix+scalar;

Any idea of what causes this behaviour and how may I fix it?

Upvotes: 2

Views: 10296

Answers (1)

Holt
Holt

Reputation: 37606

You declared the operators in the mtm namespace so the definitions should be in the mtm namespace.

Since you define them outside, you've actually two different functions:

namespace mtm {
    IntMatrix operator+(IntMatrix const&, int);
}

IntMatrix operator+(IntMatrix const&, int);

When you do matrix + scalar in operator+(int, IntMatrix const&), both functions are found:

  • The one in the namespace via Argument-Dependent Lookup.
  • The one in the global namespace since you are in the global namespace.

You need to define the operators in the namespace you declared them, mtm:

// In your .cpp
namespace mtm {

    IntMatrix operator+(IntMatrix const& matrix, int scalar) {
        // ...
    }

}

Upvotes: 6

Related Questions