c ++重载运算符bool()使用operator +给出了一个模糊的重载错误

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).有没有办法强迫这个?

再次感谢你.

Ken*_*oom 12

C++编译器允许自动转换boolint你的,这就是它想在这里做.

解决这个问题的方法是使用安全的bool习语.

从技术上讲,创建operator void*不是安全布尔成语的例子,但它在实践中是足够安全的,因为你正在运行到布尔/ INT问题是一个常见的错误,并打乱了一些非常合理的,否则正确的代码(如你从你的问题看),但void*转换的误用并不常见.

  • @didibus:安全的bool成语,当做得对,不会使那个含糊不清.您是否尝试编写`operator ==(int,MegaInt)`和`operator ==(MegaInt,int)`? (2认同)