在我自己的算术中重载运算符+
Overloading operator + in my own arithmetic
我有以下问题:假设我正在尝试实现我自己的类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
,意味着不允许从int
到MyInt
的隐式转换,然后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)
构造函数,然后由编译器隐式调用该构造函数。
相关文章:
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 重载运算符new[]的行为取决于析构函数
- 为什么将值返回函数传递给重载=运算符对运算符函数有效,而对其他运算符无效
- 在 myVector 类中重载运算符 + 时出错
- 为什么常量词在重载运算符中不与 ostream 对象一起使用<<?
- 如何在 cpp 中重载运算符 +=?
- C++ 如何重载 [] 运算符并进行函数调用
- 重载运算符的范围是什么?它是否会影响作为类成员的集合的插入函数?
- 为什么我可以在不重载 "=" 运算符的情况下将一个对象分配给另一个对象?
- 重载运算符有地址吗?
- 如何迭代重载运算符 [] 的类?
- 重载运算符与添加问题
- 模板基类中的重载运算符
- 如何调用用于重载运算符"<<"的 friend 函数?
- 在 C++17 中的命名空间和子命名空间中重载运算符是不明确的
- 重载运算符<<采用谷歌 C++ 风格
- C++ 如何正确重载 + 运算符
- cout (<<) 重载运算符不打印减去的矩阵
- 如何在 c++ 中重载运算符 + 以便能够 whrite c_str = "smth" + c_str;
- 重载运算符*以获取对另一个类的实例的引用