C++ 如何重载struct的空运算符?

C++ 如何重载struct的空运算符?,c++,struct,operator-overloading,C++,Struct,Operator Overloading,我想重载一个函数来检查struct对象是否为空 以下是我的结构定义: struct Bit128 { unsigned __int64 H64; unsigned __int64 L64; bool operate(what should be here?)(const Bit128 other) { return H64 > 0 || L64 > 0; } } 这是测试代码: Bit128 bit128; bit128.H64 =

我想重载一个函数来检查struct对象是否为空

以下是我的结构定义:

struct Bit128 {
    unsigned __int64 H64;
    unsigned __int64 L64;

    bool operate(what should be here?)(const Bit128 other) {
        return H64 > 0 || L64 > 0;
    }
}
这是测试代码:

Bit128 bit128;
bit128.H64 = 0;
bit128.L64 = 0;
if (bit128)
    // error
bit128.L64 = 1
if (!bit128)
    // error

要重载
bool
运算符:

explicit operator bool() const {
 // ...
explicit operator bool() const {
  return H64 != 0 || L64 != 0;
}
此运算符不一定是,但应该是一个
const
方法。

没有“空”运算符,但如果希望对象在布尔上下文中具有意义(例如if条件),则需要重载布尔转换运算符:

explicit operator bool() const {
 // ...
explicit operator bool() const {
  return H64 != 0 || L64 != 0;
}
请注意,显式转换运算符需要C++11。在此之前,您可以使用非显式运算符,但它有许多缺点。相反,你会想在谷歌上搜索safe bool成语。

\include
#include <cstdint>
struct Bit128 
{
    std::uint64_t H64;
    std::uint64_t L64;
    explicit operator bool () const {
        return H64 > 0u || L64 > 0u;
    }
};
结构位128 { 标准:uint64_t H64; 标准:uint64; 显式运算符bool()const{ 返回H64>0u | L64>0u; } };
您要查找的语法是
显式运算符bool()const
,它查找
运算符bool()
。作为一个不带参数的成员函数。[c]在结构或其他方面没有方法,请从现在开始相应地标记您的问题,谢谢。如果OP的用例需要隐式转换,为什么要使用
explicit
。这仍然比隐式转换更具限制性,因此它应该是声明
运算符bool
@zett42:我明白了。谢谢除非OP没有C++11可用,否则应该使用
safe bool
习惯用法,例如。G其中一个。@zett42:会更安全,是的。