【发布时间】: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); -
好吧,要添加
MyInt和int,您需要operator+(MyInt&,int) -
...或
MyInt听起来很像你可以提供一个构造函数MyInt(int)这将使转换成为可能 -
这听起来像您隐式转换为
int。通过两种方式的隐式转换,表达式只是模棱两可。隐式不好,显式好。 -
您需要提供一个完整但最小的示例供人们尝试。没有它,您只会得到诸如当前三个答案之类的愚蠢建议。由于缺乏示例而投票结束。
标签: c++ operators overloading