在C++中使用包装整数作为索引?

0 c++ operator-overloading wrapper

假设我有一个(普通的)类在C++中为随机整数包装普通的int类型,在索引数组或从字符串中选择一个字符时,如何使用这个类的实例像一个整数?

如果是运算符重载的问题,那么哪个运算符?

作为一个具体的例子,我有一个Random类,我在字符串中的随机位置选择字符,如下所示:

string chars = "whatever";
Random R = Random(0, chars.length());
other_chars += chars.at(R.getValue());
Run Code Online (Sandbox Code Playgroud)

但相反,我宁愿拥有other_chars += chars.at(R);但是怎么样?

Pra*_*ian 5

您需要一个用户定义的转换运算符.

class Random
{
  int x_;

  public:
    operator int() const { return x_; }
};
Run Code Online (Sandbox Code Playgroud)