修复重载运算符“+”的使用不明确?

1 c++ methods class operator-overloading c++11

我使用 C++11 标准编写了以下代码:

.h 文件:

#include "Auxiliaries.h"

    class IntMatrix {

    private:
        Dimensions dimensions;
        int *data;

    public:
        int size() const;

        IntMatrix& operator+=(int num);
    };
Run Code Online (Sandbox Code Playgroud)

位我得到和错误说:

错误:重载运算符“+”的使用不明确(操作数类型为“const mtm::IntMatrix”和“int”)返回矩阵+标量;

知道是什么导致了这种行为以及我该如何解决?

Hol*_*olt 5

您在mtm命名空间中声明了运算符,因此定义应该在mtm命名空间中。

由于您在外部定义它们,因此您实际上有两个不同的功能:

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

IntMatrix operator+(IntMatrix const&, int);
Run Code Online (Sandbox Code Playgroud)

当您执行matrix + scalarin 时operator+(int, IntMatrix const&),会发现两个函数:

  • 通过Argument-Dependent Lookup命名空间中的那个。
  • 全局命名空间中的一个,因为您位于全局命名空间中。

您需要定义operator命名空间中的是你宣称他们mtm

// In your .cpp
namespace mtm {

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

}
Run Code Online (Sandbox Code Playgroud)