在我自己的算术中重载operator +

时间:2015-11-26 13:27:37

标签: c++ operators overloading

我有以下问题: 假设我正在尝试实现我自己的类MyInt,它可以容纳大量数据(我知道BigNum实现 - 这只是一种做法)。我已经实现了接受int,unsigned long,unsigned long long等的构造函数。 - 因此我的问题。

我尝试使用以下声明重载operator +:

        friend MyInt operator+(const MyInt &, const MyInt &);

在课堂内。

当我添加到MyInt时,它工作正常,但是我希望它可以在像

这样的情况下工作
MyInt x(0);
x = x + 1;

当我这样称呼它时,我得到以下输出:

error: ambiguous overload for ‘operator+’ (operand types are ‘MyInt’ and ‘int’)

我很感激有关如何解决该问题的任何建议

修改

以下是我编写的示例代码。构造函数是显式

using namespace std;

class MyInt {
    public:
        MyInt() {};
        explicit MyInt(int) {};
        friend MyInt operator+(const MyInt &x, const MyInt &y) {
            MyInt result;
            cout << "operator + " << endl;
            return result;
        }   
};

int main() {
    MyInt x;
    x = x + x; //this is fine
    x = x + 1; //this is not
}

3 个答案:

答案 0 :(得分:1)

构造为explicit,表示不允许从intMyInt的隐式转换,然后operator+(const MyInt &, const MyInt &)无法应用于MyInt + int operator+

<强>解决方法1

添加MyInt operator+(const MyInt &, int); MyInt operator+(int, const MyInt &); 的重载版本,例如:

explicit

<强>溶液2

从构造函数中删除{{1}}。

答案 1 :(得分:1)

鉴于以下问题:

using namespace std;

class MyInt {
    public:
        MyInt() {};
        explicit MyInt(int) {};
        friend MyInt operator+(const MyInt &x, const MyInt &y) {
            MyInt result;
            cout << "operator + " << endl;
            return result;
        }   
};

int main() {
    MyInt x;
    x = x + x; //this is fine
    x = x + 1; //this is not
}

...合理的解决方案是使转换构造函数隐式,即非explicit

例如,std::string允许您从文字中隐式构造std::string。这提供了很大的实际好处。但是,s + s没有问题,因为指针参数没有内置+std::string不提供隐式转换回char const*

尽管如此,我认为隐式转换大数字类是有道理的。进行相反的转换,使用内置类型explicit(如果它是隐式的,则会再次弹出此问题)。最好是命名。

答案 2 :(得分:-1)

解决方案是添加operator+(const MyInt & lhs, int rhs);

另一个解决方案是添加一个MyInt(int)构造函数,然后由编译器隐式调用。

相关问题