Default values to bitfield elements

跟風遠走 提交于 2020-07-08 05:24:32

问题


In C++11 one can do

struct S {int i = 42;};

and whenever one forgets to initialize the member i, it get default initialized to 42. I Just tried this with bitfields as

struct S {int i = 42    : 5;};

and am getting

error: expected ';' before ':' token

Does this feature exist for bitfield members and if so, how do I use it?


回答1:


No, bit-fields do not allow an initializer as part of the member declaration. You can see this in the part of the grammar that describes class members (C++11 and later, [class.mem]):

member-declarator:
    declarator virt-specifier-seqopt pure-specifieropt
    declarator brace-or-equal-initializeropt
    identifieropt attribute-specifier-seqopt : constant-expression

The third form is the grammar for a bit-field declaration, but only the second form lists the brace-or-equal-initializer.




回答2:


The syntax for bit field initialization is

 struct S {int i: 5 = 42;};

and is only available in c++20: -std=c++2a for now




回答3:


You can also use a constructor to initialize a bitfield like this:

struct Foo {
    Foo () : i {15} {}

    int i : 5;
};

Foo foo;
cout << foo.i << endl; // 15

You can see it here



来源:https://stackoverflow.com/questions/27057973/default-values-to-bitfield-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!