【问题标题】:Fix use of overloaded operator '+' is ambiguous?修复重载运算符“+”的使用不明确?
【发布时间】:2020-10-02 11:01:04
【问题描述】:

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

.h 文件:

#include "Auxiliaries.h"

    class IntMatrix {

    private:
        Dimensions dimensions;
        int *data;

    public:
        int size() const;

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

我得到的一点是错误的说法:

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

知道导致此行为的原因以及如何解决它吗?

【问题讨论】:

  • 这些定义应该在 mtm 命名空间中,否则你声明了不同的函数,因此会产生歧义。
  • @smith -- 但为什么会这样呢? -- 这些是 C++ 的规则。这些实现在它们声明的命名空间之外。
  • @smith 重载函数在mtm 范围内,但您只使用using mtm::IntMatrix;using mtm::Dimensions;
  • 之前有人告诉我,我可以在.cpp文件中编写所有定义
  • @smith -- 您可以将其写入单独的 cpp。问题是你做的不对。

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


【解决方案1】:

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

因为你在外面定义它们,你实际上有两个不同的功能:

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

IntMatrix operator+(IntMatrix const&, int);

当你在operator+(int, IntMatrix const&)中做matrix + scalar时,两个函数都找到了:

  • 通过Argument-Dependent Lookup 命名空间中的那个。
  • 因为您在全局命名空间中,所以在全局命名空间中。

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

// In your .cpp
namespace mtm {

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

}

【讨论】:

  • @smith 您可能缺少定义。您应该在.cpp 文件中拥有所有三个operator+operator-。加上两个成员函数。
  • 另外,您的代码中可能存在犯了类似错误的工件,即在某些地方使用 mtm 命名空间,但在其他地方没有。
  • @smith 这是你的.h。您不能在 .h 中定义函数,除非您将它们内联,否则您将多次定义它们。
  • 但是,如果我不想在我的 cpp 文件中写入命名空间 mtm 怎么办?我不能使用 include 或 using 吗?
  • @smith 可以将命名空间添加到函数定义中:IntMatrix mtm::operator+(IntMatrix const& matrix, int scalar) { // ... }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多