我正在编译MegaInt类的一些c++代码,该类是正十进制类型的类,允许对大量数字进行算术运算。

我想重载 boolean 运算符以允许这样的代码:

MegaInt m(45646578676547676);
if(m)
    cout << "YaY!" << endl;

这是我所做的:

header :
class MegaInt
{
    public:
        ...
    operator bool() const;
};

const MegaInt operator+(const MegaInt & left, const MegaInt & right);
const MegaInt operator*(const MegaInt & left, const MegaInt & right);

执行:
MegaInt::operator bool() const
{
    return *this != 0;
}
const MegaInt operator+(const MegaInt & left, const MegaInt & right)
{
    MegaInt ret = left;
    ret += right;
    return ret;
}

现在,问题是如果我这样做:
MegaInt(3424324234234342) + 5;

它给了我这个错误:



我不知道为什么重载的bool()如何导致operator +变得big昧?

谢谢你。

好吧,每个人都给了我很好的答案,不幸的是,他们似乎都没有完全解决我的问题。

void *或Safe Bool惯用语均有效。 除了一个小问题,我希望有一个解决方法:

与0比较时,例如:
if (aMegaInt == 0)

编译器再次给出了一个模棱两可的重载错误。我知道为什么:它不知道我们要比较的是false还是值为0的MegaInt。尽管如此,在这种情况下,我希望将其转换为MegaInt(0)。有没有办法强制执行此操作?

再次感谢你。

最佳答案

允许C++编译器为您自动将bool转换为int,这就是它想要在此处执行的操作。

解决此问题的方法是使用safe bool idiom

从技术上讲,创建operator void*只是而不是,这是安全bool惯用语的一个示例,但是在实践中它是足够安全的,因为您遇到的bool/int问题是一个常见错误,会弄乱一些完全合理且正确的代码(如您从问题中看到的),但是对void*转换的误用并不常见。

关于C++重载运算符bool()使用运算符+给出了模棱两可的重载错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5306696/

10-11 23:15
查看更多