C++ 位集引用

标签 c++ c++11 std-bitset

关于bitset引用的两个问题:

Q1。有什么办法可以返回类私有(private)成员位集吗? 在下面的代码片段中(后面是输出),我试验了常规引用,但它甚至不会修改 Foo 类中的 bitset 成员。

Q2。来自 this question 中的答案,我知道常规引用没有足够的粒度来指向存储在 bitset 中的单个位,因为 bitset 以更紧凑的形式存储它们。但是,如果这是真的,我的代码如何仍然设法修改 b3[1] = 0 行中 b3 的第一位?

#include <iostream>
#include <bitset>

using namespace std;

class Foo 
{ 
private:
    bitset<4> b1;  
public:
    inline void print_value() 
    {
        cout << "The bitset b1 is: ( "<< b1 << " )" << endl;
    }
    inline void set_all() { b1.set(); }
    inline bitset<4> get_b1() { return b1; }
    inline bitset<4>& get_b1_ref() { return b1; }
}; 

int main()
{
    Foo f;
    f.print_value();
    f.set_all();
    f.print_value();
    auto b2 = f.get_b1();
    b2.flip();
    cout << "The bitset b2 is: ( "<< b2 << " )" << endl;
    f.print_value();
    auto b3 = f.get_b1_ref();
    cout << "The bitset b3 is: ( "<< b3 << " )" << endl;
    cout << "b3[0] is ( " << b3[0] << " )"<< endl;
    cout << "b3[0] is ( " << b3[1] << " )"<< endl;
    b3[1] = 0;
    cout << "The bitset b3 after change is: ( "<< b3 << " )" << endl;
    f.print_value();
}

Output:
The bitset b1 is: ( 0000 )
The bitset b1 is: ( 1111 )
The bitset b2 is: ( 0000 )
The bitset b1 is: ( 1111 )
The bitset b3 is: ( 1111 )
b3[0] is ( 1 )
b3[0] is ( 1 )
The bitset b3 after change is: ( 1101 )
The bitset b1 is: ( 1111 )

最佳答案

auto b3 = f.get_b1_ref();

推导类型将不是是一个引用,只有基类型 bitset<4> .这意味着 b3不是引用,所有修改 b3否则其内容将限于 b3对象本身。

要获得引用,您需要明确使用 &在声明中:

auto& b3 = f.get_b1_ref();

关于C++ 位集引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58749023/

相关文章:

c++ - 高性能 QImage 输出显示

c++ - 将字符串分配给指针数组

c++ - 使用 for 循环创建条形图

c++ - 如何将nana编译成静态库

c++ - 如何将位集类型的所有位初始化为 1

c++ - 如何将 std::bitset<N> 转换为 std::bitset<M>?

c++ - OpenGL 和 SDL '#version required and missing' 但在调试中工作

c++ - 像GCC这样的编译器如何实现std::mutex的获取/释放语义

c++ - 如何在普通C++ 11中创建不同对象 “generators”的层次结构

c++ - 将枚举类与 std::bitset 一起使用