简体   繁体   中英

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. But here you can see that explicit assign of a integer works fine.

#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= . Compiler will, however, generate one (see this question). You can actually check that using 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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