gpt4 book ai didi

c++ - 可以在 C++ 类中使用位域吗?

转载 作者:可可西里 更新时间:2023-11-01 16:36:46 26 4
gpt4 key购买 nike

在 C 结构中,可以像这样指定不同于默认类型的位长度的另一个位长度:

struct MyStruct{
int myVar : 1; //Size of myVar is 1 bit (so it can take values 0 or 1
int myOtherVar: 4; //Size of myOtherVar is 4 bits (so it can take values 0 to 15)
}

这称为位域。

我的问题是是否也可以在 C++ 类中执行此操作,如下所示:

class MyClass{
public:
//Some methods
private:
int m_myAttribute : 1;
int m_myOtherAttribute : 4;
}

我在网上搜索了这个,但我发现的所有位域示例都使用了结构,而不是类。

我测试了这段代码,它编译得很好,但我想知道属性的大小是否真的是指定的大小,或者编译器是否只是忽略了位域并使用了标准的 int 尺寸。

最佳答案

是的, 可以有位域成员。在 C++ 中,除了默认访问级别和默认继承类型外,classstruct 之间没有区别。它们都称为类类型。如果您可以在 struct 中做某事,那么您也可以在 class 中做同样的事情。由于默认访问级别不同,它们看起来会有些不同,但您得到的是相同的东西。例如

struct foo
{
int m_myAttribute : 1;
int m_myOtherAttribute : 4;
int m_myOtherOtherAttribute : 27;
};

相同
class bar
{
public:
int m_myAttribute : 1;
int m_myOtherAttribute : 4;
int m_myOtherOtherAttribute : 27;
};

请注意,我们必须在类中使用 public:,因为默认情况下成员是私有(private)的。

现在谈谈 C++ 中位域的大小。 [class.bit]/1 包含您需要的所有信息:

The constant-expression shall be an integral constant expression with a value greater than or equal to zero. The value of the integral constant expression may be larger than the number of bits in the object representation (3.9) of the bit-field’s type; in such cases the extra bits are used as padding bits and do not participate in the value representation (3.9) of the bit-field. Allocation of bit-fields within a class object is implementation-defined. Alignment of bit-fields is implementation-defined. Bit-fields are packed into some addressable allocation unit. [ Note: Bit-fields straddle allocation units on some machines and not on others. Bit-fields are assigned right-to-left on some machines, left-to-right on others. —end note ]

强调我的

从这里我们得到位域的大小至少是底层数据类型的大小,但是如果你过度分配空间那么额外的空间就会变成填充并且不会用于位的值- 现场成员。

关于c++ - 可以在 C++ 类中使用位域吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40655160/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com