鍍金池/ 問(wèn)答/C++/ c++ 結(jié)構(gòu)體中operator int()方法是什么意思?

c++ 結(jié)構(gòu)體中operator int()方法是什么意思?

在boost.DI上看到一個(gè)結(jié)構(gòu)體寫(xiě)法以前沒(méi)有見(jiàn)過(guò),這個(gè)結(jié)構(gòu)體中的方法是什么意思?

struct width {
  int value;
  constexpr operator int() const { return value; }
};
struct height {
  int value;
  constexpr operator int() const { return value; }
};



class button {
public:
  button(width, height); // strong constructor interface
};
button{width{10}, height{15}};
回答
編輯回答
笨笨噠

類型轉(zhuǎn)換

#include <iostream>

struct width{
    int w;
    constexpr operator int()const {
        return w;
    }
};
int main(void)
{
    width w{8};
    int i = w; // 隱式轉(zhuǎn)換
    int j = int(w); // 顯式
    int k = width(w);

    std::cout<<i<<j<<k;
}
---
888

附:參考鏈接

2017年9月23日 05:11