修复重载运算符“ +”的使用不明确吗? [英] Fix use of overloaded operator '+' is ambiguous?

查看:322
本文介绍了修复重载运算符“ +”的使用不明确吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I wrote the following code using C++11 standard:

.h文件:

#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:


错误:使用重载运算符'+'是模棱两可的(操作数类型为
'const mtm :: IntMatrix'和'int ')
return matrix + scalar;

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?

推荐答案

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

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);

当您在矩阵+标量中执行 operator +(int,IntMatrix const&),找到两个函数:

When you do matrix + scalar in operator+(int, IntMatrix const&), both functions are found:

您需要定义操作符在您声明它们的命名空间中, mtm

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) {
        // ...
    }

}

这篇关于修复重载运算符“ +”的使用不明确吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆