Fix use of overloaded operator '+' is ambiguous?

对着背影说爱祢 提交于 2020-06-29 03:57:05

问题


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 operators 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!