C++转换操作符

Conversion Operator

operator type();

type表示内置类型名、类类型名、类型别名。不可转换为数组和函数类型,可转换为指针和引用类型。

class SmallInt {
public:
  SmallInt(int i = 0) : val(i) {
    if (i < 0 || i > 255)
      throw std::out_of_range("Bad SmallInt intializer");
  }
  operator int() const {
    return val;
  }
private:
  std::size_t val;
};

应用:

int calc(int);

SmallInt si;
int i = calc(si);

可以自动调用转换。

原文地址:https://www.cnblogs.com/chenkkkabc/p/3132055.html