是否可以重载索引operator []以从整数返回位?

mer*_*011 0 c++ operator-overloading operators bitwise-operators

我不确定这是否可行,因为据我所知,引用不能引用整数中的各个位,但我很想知道是否有一种技术可以实现以下效果.

int z = 0x1234;
z[0] = 1; //set the most significant bit of z.
uint8_t bit = z[30] //get the index 30 bit of z, counting from the left.
Run Code Online (Sandbox Code Playgroud)

如果我不能z[0] = 1,我想知道是否至少可以使用重载操作提取位.

Luc*_*ore 5

不是直接的.你可以写一个包装器int或使用一个std::bitset.

  • @ merlin2011:你不能完全模仿`int`.例如,从"int"到"long"的转换是内置的,因此它可以参与包含用户定义转换的转换链.从您的类型到"long"的转换将由用户定义,因此将在任何链中的一个用户定义转换的限制内运行.你可以给你的类型提供与`int`相同的运算符,AFAIK只有转换的行为与`int`的保证行为不同. (2认同)