整数c ++包装器

Ste*_*tef 0 c++ int wrapper

我在C++中做了一个非常小而简单的Integer类包装器,其中globaly看起来像这样:

class Int
{
  ...
private:
  int value;
  ...
}
Run Code Online (Sandbox Code Playgroud)

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

例如:

Int myInteger(45);
int x = myInteger;
Run Code Online (Sandbox Code Playgroud)

jua*_*nza 7

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

class Int
{
 public:
  operator int() const { return value; }
 ...
};
Run Code Online (Sandbox Code Playgroud)

这允许以下初始化 int

int x = myInteger;
Run Code Online (Sandbox Code Playgroud)

在C++ 11中,您可以决定是将该转换限制为int,还是允许进一步转换int为其他转换.要限制int,请使用explicit转换运算符:

explicit operator int() const { return value; }
Run Code Online (Sandbox Code Playgroud)

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