在 C++ 中使用包装整数作为索引?
假设我有一个(简单的)类,它将 C++ 中的普通 int 类型包装为随机整数,那么在索引数组或从字符串中选取字符时,如何像整数一样使用此类的实例?
如果是运算符重载的问题,那么哪个运算符重载?
作为一个具体的例子,我有一个 Random 类,我在字符串中的随机位置选择字符,如下所示:
string chars = "whatever";
Random R = Random(0, chars.length());
other_chars += chars.at(R.getValue());
但是,我宁愿有 other_chars += chars.at(R);
但是如何?
Assuming I have a (trivial) class that wraps normal int type in C++ for random integers, how can I use an instance of this class like an integer when indexing an array or picking a character from a string?
If it's a matter of operator overloading, then which operator?
As a specific example, I have a Random class and I pick characters at random locations in a string like this:
string chars = "whatever";
Random R = Random(0, chars.length());
other_chars += chars.at(R.getValue());
But instead, I'd rather have other_chars += chars.at(R);
But how?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要 用户定义的转换运算符。
You need a user defined conversion operator.
您是否尝试过在包装器
Random
内重载operator int()
。我相信它应该是这样的,Have you tried overloading
operator int()
inside the wrapperRandom
. I believe it should be something like,您需要类型转换运算符重载:operator int() { return _value; }。
这里是更多解释。
You need typecast operator overloading:
operator int() { return _value; }
.Here is more explanation.