Did*_* A. 9 c++ boolean operator-overloading
我正在编译MegaInt类的一些c ++代码,这是一个正十进制类,允许对大数字进行算术运算.
我想重载operator bool以允许这样的代码:
MegaInt m(45646578676547676);
if(m)
cout << "YaY!" << endl;
Run Code Online (Sandbox Code Playgroud)
这就是我做的:
标题:
class MegaInt
{
public:
...
operator bool() const;
};
const MegaInt operator+(const MegaInt & left, const MegaInt & right);
const MegaInt operator*(const MegaInt & left, const MegaInt & right);
Run Code Online (Sandbox Code Playgroud)
执行:
MegaInt::operator bool() const
{
return *this != 0;
}
const MegaInt operator+(const MegaInt & left, const MegaInt & right)
{
MegaInt ret = left;
ret += right;
return ret;
}
Run Code Online (Sandbox Code Playgroud)
现在,问题是如果我这样做:
MegaInt(3424324234234342) + 5;
Run Code Online (Sandbox Code Playgroud)
它给了我这个错误:
'operator +'中的'operator +'的模糊重载'(const MegaInt&,const MegaInt&)注意:候选者是:operator +(int,int)| 注意:const MegaInt运算符+(const MegaInt&,const MegaInt&)|
我不知道为什么.如何导致操作符+的重载bool()变得模棱两可?¸
谢谢.
好吧,不幸的是,每个人都给了我很好的答案,他们似乎都没有完全解决我的问题.
void*或Safe Bool Idiom都可以使用.除了一个小问题,我希望有一个解决方法:
与0比较时:
if (aMegaInt == 0)
Run Code Online (Sandbox Code Playgroud)
编译器再次出现模糊的重载错误.我理解为什么:它不知道我们是在比较假,还是在比较值为0的MegaInt.尽管如此,在这种情况下,我希望它转换为MegaInt(0).有没有办法强迫这个?
再次感谢你.
| 归档时间: |
|
| 查看次数: |
20181 次 |
| 最近记录: |