简体   繁体   English

为 Bitset 赋值

[英]Assign a value to Bitset

I'm curious to know why the following code is working, According to bitset template class. you can assign a value to bitset (int or binary representation as string) by constructor but not after that.我很想知道为什么以下代码有效,根据 bitset 模板 class。您可以通过构造函数为 bitset(int 或二进制表示形式的字符串)分配一个值,但之后不能。 But here you can see that explicit assign of a integer works fine.但在这里您可以看到 integer 的显式分配工作正常。

#include <iostream>
#include <bitset>
#include <string>
using namespace std;

int main()
{
    bitset<8> b(string("101"));
    cout << b.to_ullong()<<"\n";
    b= 145;
    cout << b<<"\n";
    return 0;
}

this question also might be relevant.这个问题也可能是相关的。 How to assign bitset value from a string after initializaion 初始化后如何从字符串中分配位集值

Bitset's non-string constructors are implicit . 位集的非字符串构造函数是隐式的

If they were declared as explicit you would indeed have to write 如果将它们声明为显式的,则确实需要编写

b = bitset<8>(145);

What might seem confusing is the fact that std::bitset does not explicitly define operator= .令人困惑的是std::bitset没有明确定义operator= Compiler will, however, generate one (see this question).但是,编译器会生成一个(请参阅问题)。 You can actually check that using cppinsight .您实际上可以使用cppinsight检查。 This means that, in combination with the implicit constructor mentioned in the accepted answer, your code works.这意味着,结合接受的答案中提到的隐式构造函数,您的代码可以正常工作。 You can see the constructor call and subsequent assignment in the cppinsight example.您可以在 cppinsight 示例中看到构造函数调用和后续赋值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM