c++ - 修复重载运算符 '+' 的使用不明确?

标签 c++ class c++11 methods operator-overloading

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

.h文件:

#include "Auxiliaries.h"

    class IntMatrix {

    private:
        Dimensions dimensions;
        int *data;

    public:
        int size() const;

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

我得到的位和错误的说法是:

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

知道是什么原因导致了这种行为,我该如何解决?

最佳答案

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

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

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

IntMatrix operator+(IntMatrix const&, int);

当您在 operator+(int, IntMatrix const&) 中执行 matrix + scalar 时,会找到两个函数:

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

您需要在声明它们的命名空间中定义operatormtm:

// In your .cpp
namespace mtm {

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

}

关于c++ - 修复重载运算符 '+' 的使用不明确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62347462/

相关文章:

c# - 添加到类中的列表

c++ - 从构造函数调用类函数还是使用智能指针?

c++ - 链接器错误:无法解析构造函数

C++阅读播放列表没有专辑的特定分隔符

c++ - 仅当没有其他转换可用时如何启用构造函数模板?

c++ - 如何使用list的unique_ptr的C++ unordered_map

c++ - 使用 C++ 随时随地运行更改 CMD 命令

c++ - 我在 g++ 中的(简单)代码链接,在 clang 中没有链接

python-3.x - 具有相同输入的两个 python(3) 类(扩展一个 python 类)

c++ - 是否可以更改C++程序本身的代码?