整数c ++包装器

时间:2013-06-09 17:29:40

标签: c++ int wrapper

我正在用C ++做一个非常小而简单的Integer类包装器,它的整体看起来是这样的:

class Int
{
  ...
private:
  int value;
  ...
}

我处理了几乎所有可能的任务,但我不知道我必须使用什么样的操作才能获得原生左派。

例如:

Int myInteger(45);
int x = myInteger;

1 个答案:

答案 0 :(得分:7)

您可能希望转换运算符转换为int:

class Int
{
 public:
  operator int() const { return value; }
 ...
};

这允许以下初始化int

int x = myInteger;

在C ++ 11中,您可以决定是否将转化限制为int,或者是否允许从int进一步转换为其他内容。要限制为int,请使用explicit转换运算符:

explicit operator int() const { return value; }

虽然在这种情况下可能没有必要。