簡體   English   中英

重載運算符| 干擾Qt枚舉常量

[英]Overloading operator | interferes with Qt enum constants

我使用作用域枚舉創建位標志,並且重載了operator | 合並值:

enum class PARAM_T : int {
    NONE = 0x0,
    INPUT = 0x01,
    OUTPUT = 0x02,
    OUTPUT_VECTOR = 0x04
};

inline PARAM_T operator | (PARAM_T lhs, PARAM_T rhs)
{
    using T = std::underlying_type_t<PARAM_T>;
    return (PARAM_T)(static_cast<T>(lhs) | static_cast<T>(rhs));
}

在項目的其他地方,我使用Qt小部件執行一些拖放操作,在這里我使用operator | 合並一些命名常量:

Qt::DropAction dropAction = drag->exec(Qt::CopyAction | Qt::MoveAction);

operator | 這里與我的位標志無關,但是由於某種原因,我的重載破壞了這一行代碼,並產生以下錯誤:

error C2664: 'Qt::DropAction QDrag::exec(Qt::DropActions,Qt::DropAction)' : cannot convert argument 1 from 'int' to 'Qt::DropActions'

為什么編譯器將Qt常量與我的重載匹配? 它們是完全不同且不兼容的類型。

閱讀有關標志的主題,我發現有一些反對將枚舉用作標志的論點,因此我將枚舉更改為:

namespace PARAM {
    const int NONE =            0;
    const int INPUT =           1 << 0;
    const int OUTPUT_SCALAR =   1 << 1;
    const int OUTPUT_VECTOR =   1 << 2;
}

現在,我可以使用operator |的默認實現。 operator &等,而不是我的重載,Qt再次感到高興。 這更多的是替代方法,而不是答案。 我仍然想知道為什么編譯器將我的重載用於Qt常量。

暫無
暫無

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

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