gpt4 book ai didi

c++ Overload operator bool() 使用 operator+ 给出模糊的重载错误

转载 作者:可可西里 更新时间:2023-11-01 16:29:25 26 4
gpt4 key购买 nike

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

我想重载 operator bool 以允许这样的代码:

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

这是我做的:

标题:

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;

它给我这个错误:

ambiguous overload for 'operator+' in 'operator+(const MegaInt&, const MegaInt&) note: candidates are: operator+(int, int) | note: const MegaInt operator+(const MegaInt&, const MegaInt&)|

我不知道为什么。重载的 bool() 是如何导致 operator+ 变得模棱两可的?¸

谢谢。


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

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

与 0 比较时喜欢:

if (aMegaInt == 0)

编译器再次给出了不明确的重载错误。我明白为什么:它不知道我们是在与 false 还是与值 0 的 MegaInt 进行比较。尽管如此,在那种情况下,我希望它转换为 MegaInt(0)。有没有办法强制执行此操作?

再次感谢您。

最佳答案

允许 C++ 编译器自动将 bool 转换为 int,这就是它在这里要做的。

解决这个问题的方法是使用 safe bool idiom .

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

关于c++ Overload operator bool() 使用 operator+ 给出模糊的重载错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5306696/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com