c++ 结构体中operator int()方法是什么意思?

在boost.DI上看到一个结构体写法以前没有见过,这个结构体中的方法是什么意思?

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}};
阅读 8.1k
1 个回答

类型转换

#include <iostream>

struct width{
    int w;
    constexpr operator int()const {
        return w;
    }
};
int main(void)
{
    width w{8};
    int i = w; // 隐式转换
    int j = int(w); // 显式
    int k = width(w);

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

附:参考链接

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题