簡體   English   中英

如何重載struct的空操作符?

[英]How can I overload empty operator of struct?

我想重載一個函數來檢查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 {
 // ...

此運算符不必是,但應該是const方法。

#include <cstdint>
struct Bit128 
{
    std::uint64_t H64;
    std::uint64_t L64;
    explicit operator bool () const {
        return H64 > 0u || L64 > 0u;
    }
};

沒有“空”運算符,但如果您希望對象在布爾上下文中具有重要性(例如if-conditions),則需要重載布爾轉換運算符:

explicit operator bool() const {
  return H64 != 0 || L64 != 0;
}

請注意,顯式轉換運算符需要C ++ 11。 在此之前,您可以使用非顯式運算符,但它有許多缺點。 相反,你會想谷歌的安全布爾成語。

您正在尋找的語法是explicit operator bool() const它在c ++ 11及更高版本中是安全的

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM