【问题标题】:Overloading operator + in my own arithmetic [closed]在我自己的算术中重载运算符 + [关闭]
【发布时间】:2016-02-29 15:01:27
【问题描述】:

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

我正在尝试使用以下声明重载运算符 +:

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

在课堂内。

当我添加到 MyInt's 时它工作正常,但是我希望它在像这样的情况下工作

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
}

【问题讨论】:

  • 尝试使用x = x + MyInt(1);
  • 好吧,要添加MyIntint,您需要operator+(MyInt&amp;,int)
  • ...或MyInt 听起来很像你可以提供一个构造函数MyInt(int) 这将使转换成为可能
  • 这听起来像您隐式转换为int。通过两种方式的隐式转换,表达式只是模棱两可。隐式不好,显式好。
  • 您需要提供一个完整但最小的示例供人们尝试。没有它,您只会得到诸如当前三个答案之类的愚蠢建议。由于缺乏示例而投票结束。

标签: c++ operators overloading


【解决方案1】:

构造为explicit,表示不允许intMyInt的隐式转换,则operator+(const MyInt &amp;, const MyInt &amp;)无法申请MyInt + int的调用。

解决方案1

添加operator+的重载版本,如:

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

解决方案2

从构造函数中删除explicit

【讨论】:

  • Re (1),为所有参数类型组合提供重载是不切实际的。
  • @Cheersandhth.-Alf OP 有理由使用显式 ctor,所以我把它作为第一个解决方案。 -> “我试图避免在构造函数中使用 char 或 bool”
【解决方案2】:

鉴于以下问题:

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(如果它是隐式的,那么这个问题会再次弹出)。并最好命名。

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

    • 第一个不切实际,第二个已经做好了。
    • 鉴于您的构造函数是显式的,因此不可能进行隐式转换。这就是问题;)
    猜你喜欢
    • 1970-01-01
    • 2010-12-10
    • 1970-01-01
    • 2020-03-10
    • 2012-03-11
    相关资源
    最近更新 更多