在我自己的算术中重载运算符+

Overloading operator + in my own arithmetic

本文关键字:重载 运算符 我自己 自己的      更新时间:2023-10-16

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

我正试图用以下声明重载运算符+:

        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
}

构造为explicit,意味着不允许从intMyInt的隐式转换,然后operator+(const MyInt &, const MyInt &)不能应用于MyInt + int的调用。

解决方案1

添加operator+的过载版本,例如:

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

解决方案2

从构造函数中删除explicit

给定以下问题:

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进行相反的转换(如果它是隐式的,那么这个问题会再次出现)。最好命名。

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

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