簡體   English   中英

為作用域枚舉類類型重載 ++ 運算符

[英]Overloading ++ operator for a scoped enum class type

我一直在試驗 c++ 的 enum 類特性,並成功地使 ++ 運算符重載如下:

enum class counter_t : uint8_t {VAL1 = 0, VAL2, VAL3, VAL4, END};

inline counter_t operator ++ (counter_t c, int) {
  counter_t c2;
  if (c == counter_t::END) {
  c2 = counter_t::VAL1;
    }
  else {
  c2 = (counter_t)((uint8_t)c + 1);
  }
  return (c2);
}

int main(void) {

  volatile counter_t x = counter_t::VAL1;
  x = x++;
  x++;

  while(1) {
    //do stuff
  }
}

非常坦率的。 “x=x++;” 線工作正常,但是“x++;” 線沒有。 自動增量版本的 ++ 運算符函數的正確形式是什么?

您可以使用它來實現前綴增量:

inline counter_t& operator ++ (counter_t& c) {
  if (c == counter_t::END)
      c = counter_t::VAL1;
  else
      c = counter_t(unsigned(c) + 1);
  return c;
}

現在,您可以使用前綴增量來實現后綴增量:

inline counter_t operator ++ (counter_t& c, int) {
  counter_t result = c;
  ++c;
  return result;
}

測試:

#include <iostream>
int main(void) {
    counter_t prefix = counter_t::VAL1;
    for(unsigned i = 0; i < 5; ++i)
        std::cout << unsigned(++prefix) << ' ';
    std::cout << '\n';

    counter_t postfix = counter_t::VAL1;
    for(unsigned i = 0; i < 5; ++i)
        std::cout << unsigned(postfix++) << ' ';
    std::cout << '\n';
}

注意:在每種情況下,計數器都是通過引用獲取並進行修改的。

僅在錯誤之后,以下代碼編譯運行並在 MSVC 上正常工作。 注意函數參數中的volatile& 還有c2 = c和一些修改,以遵循 ++ 標准(返回值,然后遞增)。 volatile是必需的,因為您已將 x 聲明為volatile

inline counter_t operator ++ (volatile counter_t &c, int) 
{
    counter_t c2;

    if (c == counter_t::END)
        c2 = counter_t::VAL1;
    else
        c2 = static_cast<counter_t>(static_cast<uint8_t>(c) + 1);

    c = c2;

    return c2;
}

暫無
暫無

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

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