问题
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?
回答1:
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 operator
s in the namespace you declared them, mtm
:
// In your .cpp
namespace mtm {
IntMatrix operator+(IntMatrix const& matrix, int scalar) {
// ...
}
}
来源:https://stackoverflow.com/questions/62347462/fix-use-of-overloaded-operator-is-ambiguous