`

c++ - union and the bitfields

    博客分类:
  • c++
c++ 
阅读更多

C++ has some good compatability with the C language, which offers good support for low-level machine level programming construct, the union and the bitfield are two examples of such...

 

 

Union

 

 

the union is a special kind of class, the data members inside the union are stored in memory in such a way that they overlap with each other.

 

that's said, it means the union should have the following.

 


what a union can have

  • it can contain public/private access modifier
  • it can contains constructor or destructor
  • it can conly copy assignment operator or something...

 

 

while what union cannot have:

  • it cannot have member who has contructor, destructor, or copy assignment operator
  • it cannot have static member functions
  • It cannot have reference members such as int &rfi;

 

First, let's suppose that we have a lex parser, which can pase

 

int i = 0;

 

 

to a sequence of symbols

 

Type, ID, Assign, Constant, Semicolon;

 

so, we can define a enum to represent each type of the symbols.

 

 

enum TokenKind 
{
	Type, 
	ID, 
	Assign, 
	Constant,
	Semicolon
};
 

and we have to define a union that can reprent the values of the datas of the symbols.

 

union TokenValue {

public :
	TokenValue()  {}
	TokenValue(int ix_ ): _ival(ix_) {}
	TokenValue(char ch_) : _cval(ch_) {}
	TokenValue(char * sval_): _sval(sval_) {}
	TokenValue(double dval_) : _dval(dval_) {}

	int ival() { return _ival; } 
	char cval() { return _cval; }
	char * sval() { return _sval;} 
	double dval() { return _dval;} 

	char _cval;
	int _ival;
	char *_sval;
	double _dval;
};

class Token 
{
public:
	TokenKind tok;
	TokenValue val;
};
 

As you can see, the union type TokenValue has access modifier, it has the member functions, and it has constructors.

 

To use the union, we can define a class which has both the union as the value and a enum as the indicator which tracks the type of value stored inside the union.

 

 

here is one simple code .

 

 

TokenKind parse() 
{
	return ID;
}
/*
*  below shows you how to use the union, it is a best practise to keep a token kind to keep track of what type of data is stored in the union type. 
*/
int lex() {
	Token curToken;
	char * curString;
	int curIVal;
	switch (parse()) { 
	case ID:
		curToken.tok = ID;
		curToken.val._sval  = curString;
		break;
	case Constant:
		curToken.tok = Constant;
		curToken.val._ival = curIVal;
		break;
	default:
		break;
	}

	return 0;
}

 

Bit fields

A specied class data member , referenced to as bit-fields, can be declared to hold a specified number of bits. A bit fields must have an integral data type, It can either signed or unsigned.

 

/**
*bit fiels
*  bit fiels is a space saving member
*/

typedef unsigned int Bit;

class File {
public:
	Bit mode: 2;
	Bit modified : 1;
	Bit prot_owner : 3;
	Bit prot_group : 3; 
	Bit prot_world : 3; 

	void write();
	void close();
};

void File:: write() {
	modified = 1;
}


void File::close() {
	if (modified) {
		// ... save contents
	}
}

enum { READ = 01, WRITE = 02 } ;

int test_bitfields() {
	File myfile ; 

	myfile.mode != READ;

	if (myfile.mode & READ) { 
		cout << "myfile.mode is set to READ \n";
	}
}
 

 

 

 

 

 

分享到:
评论

相关推荐

    华为内部教材:C++中级培训教程(PPT)

    类可以包含命名空间(namespace)、类名(class names)、成员变量(class members)、成员函数(member functions)、静态成员函数(static member functions)、联合体(union)、位域(C++ Bit Fields)、嵌套类(nested class ...

    C++ 旅程

    #### 一、C/C++中的位域(Bit Fields) **概念解释:** 位域(Bit Fields),也被称为位段,是C/C++中的一种特殊的数据结构,它允许在一个整数类型(通常是`unsigned int`)中定义一系列具有固定宽度的字段,每个...

    华为C++中级培训胶片ppt

    类名称、成员变量、成员函数(包括普通成员函数和静态成员函数)、联合体(Union)、位域(Bit Fields)、嵌套类声明、类型名在类作用域内的定义、多重继承、虚函数、抽象类以及控制类成员访问权限(private、...

    C.Programming.Professional.For.Beginners.B011A2PX30

    Structure, Union, Enum, Bit Fields, Typedef. Chapter 11. Console Input and Output. Chapter 12. File Handling In C. Chapter 13. Miscellaneous Topics. Chapter 14. Storage Class. Chapter 15. Algorithms....

    C.Programming.Step.By.Step.Beginners.To.Experts.Edition.B011EXMV7Q

    Structure, Union, Enum, Bit Fields, Typedef. Chapter 11. Console Input and Output. Chapter 12. File Handling In C. Chapter 13. Miscellaneous Topics. Chapter 14. Storage Class. Chapter 15. Algorithms....

    嵌入式C、C++语言精华.pdf

    - **实现方式**: 使用`bit-fields`。 - **应用场景**: 在资源受限的嵌入式系统中特别有用。 #### 13. **C/C++中的近指令、远指针和巨指针** - **定义**: - **近指令**: 指向当前段的指针。 - **远指针**: 指向...

    面向对象程序设计c++

    10. 联合(Union)和位字段(Bit Fields):联合用于存储不同类型的数据,但共享同一块内存空间。位字段则允许在结构或类中定义具有固定大小的成员,节省存储空间。 以上是C++中面向对象编程的一些基本概念和特性。...

    华为最新c++培训胶片200906

    课程介绍了命名空间(namespace)、类名(class names)、类成员(class members)包括成员函数(member functions)、静态成员函数(static member functions)、联合体(union)、位字段(C++ Bit Fields)、嵌套类声明(nested ...

    华为C++中级培训教程.ppt

    在类中,可以声明命名空间(namespace)以避免命名冲突,定义类成员包括成员函数、静态成员函数、联合(union)、位字段(bit fields)、嵌套类(nested class)、类型名(type names in class scope)以及多重基类(multiple ...

    C/C++笔试题

    位域(bit fields)允许在结构体中定义具有固定位数的成员。这在某些应用场景下可以节省内存空间,如硬件接口编程。位域的使用需要特别小心,因为它们的行为可能依赖于特定的编译器和处理器架构。 #### 27. 字符串...

    嵌入式C C++语言精华文章

    - **位域操作**:通过使用位域(`bit fields`),可以在单个`struct`成员中表示多个布尔值或枚举值,从而节省空间资源。 #### C++中extern "C"含义深层探索 **知识点概述**:`extern "C"`是C++中用于处理C和C++混合...

    c++培训ppt

    C++位字段(bit fields),用于节省内存;嵌套类声明(nested class declarations),将一个类定义在另一个类的内部;类型名称在类作用域(type names in class scope)中声明,使得类能有自己的类型;多重继承,一...

    c c++位域研究总结!!!

    位域(Bit-fields)是 C 语言和 C++ 语言中都有的一个概念,但是位域有很多需要注意的问题。其中一个重要的问题是大端和小端字节序的问题。 大端和小端字节序是计算机科学中的一种约定,用于描述多字节数字在计算机...

    嵌入式CC++语言精华文章集锦

    - **位域(Bit Fields)**: 可以在一个整数类型中定义多个位作为单独的变量使用,节省内存空间。 **1.4 示例** 以下是一个示例,展示了如何使用结构体和联合体来实现一种通用的通信协议: ```c typedef struct { ...

    嵌入式C语言精华的pdf文件

    - 使用位字段(bit fields)来节省空间,尤其是在资源受限的嵌入式环境中。 - 对于需要频繁访问的成员,考虑将其放在结构体的开头以提高访问速度。 ##### 2. C++中extern "C"含义深层探索 - **定义**: `extern "C"`...

    嵌入式C精华

    - **位字段**:介绍了如何在结构体中定义位字段(bit fields),这是一种特殊的数据布局方式,可用于节省内存空间。 - **应用场景**:在嵌入式系统中,为了优化内存使用,经常会使用位字段。 ### 12. C/C++中的近...

    嵌入式高级C语言进阶-第五讲 数据结构与链表

    ##### 1.1 字段(BitFields) 在C语言中,结构体还可以包含**字段**,这是一种特殊的结构体成员,可以用来压缩存储空间。字段允许我们将多个成员放入同一个字节或更大的存储单元中,从而节省内存空间。字段通常用于...

Global site tag (gtag.js) - Google Analytics