如何使operator[]返回对unsigned int中各个位的引用?
我正在制作一个 vector
实现。我保存一个无符号整数并使用按位运算来获得 true 和 false 的向量。我的问题是这样的;我可以通过操作符[]访问各个位,但是如何获得对这样一个位的引用,以便我可以写
Vector<bool> v(5, true);
v[3] = false;
在我听说你不应该对各个位进行引用/指针的地方。用于检索位值的代码摘要:
...
unsigned int arr; // Store bits as unsigned int
unsigned int size_vec; // The size of "bool vector"
...
bool& Vector<bool>::operator[](unsigned int i) {
if (i>=vec_size || i<0) {
throw out_of_range("Vector<bool>::operator[]");
}
int index = 1 << (i-1);
bool n = false;
if (index & arr) {
n=true;
}
return n;
};
那么,如何返回某种可以更改各个位的引用呢?
I'm making a vector<bool>
implementation. I save an unsigned int and use bitwise operations to have a vector of true and false. My problem is this; I can access individual bits by operator[], but how do I get a reference to such a bit so I can write
Vector<bool> v(5, true);
v[3] = false;
Somewhere I heard that you shouldn't do references/pointers to individual bits. A summary of the code, that works for retrieving bit value:
...
unsigned int arr; // Store bits as unsigned int
unsigned int size_vec; // The size of "bool vector"
...
bool& Vector<bool>::operator[](unsigned int i) {
if (i>=vec_size || i<0) {
throw out_of_range("Vector<bool>::operator[]");
}
int index = 1 << (i-1);
bool n = false;
if (index & arr) {
n=true;
}
return n;
};
So, how can you return some sort of reference making it possible to change the individual bits?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您需要使用适当的运算符重载来定义代理对象,以便它的行为类似于bool&,但寻址各个位。这就是
std::vector
的作用。像这样的事情:
一般来说,我建议避免像这样依赖于 C++ 中偷偷摸摸的隐式转换的事情,因为它确实会扰乱你的直觉,并且它不能很好地与
auto
和等事情一起使用C++11 中的 decltype
。You need to define a proxy object with the appropriate operator overloads so that it acts like
bool&
but addresses individual bits. This is whatstd::vector<bool>
does.Something like this:
Generally I would recommend avoiding things like this that rely on sneaky implicit conversions in C++ because it really messes with your intuition, and it doesn't play nicely with things like
auto
anddecltype
in C++11.您不能通过返回对 bool 的引用来做到这一点。您需要创建并返回一个代理对象,并重载其赋值运算符,例如
You cannot do that by returning a reference to bool. You need to create and return a proxy object instead, and overload its assignment operator, something like
你不能。
你最好的选择是返回一个代理对象。
起点:
You can't.
You're best bet would be to return a proxy object.
Starting point:
您不能引用各个位。您只能引用变量。
您可以做的最重要的事情是创建一个代理类,它公开对 bool 的引用,并维护对基本整数的内部引用以及必要的位处理机制;然后让您的
[]
运算符返回这样的代理对象。You cannot have references to individual bits. You can only have references to variables.
The closes thing you could do is make a proxy class which exposes a reference to a
bool
and which maintains an internal reference to the base integer as well as the necessary bitfiddling mechanics; then make your[]
-operator return such a proxy object.