【Suatin】不学编译原理就制作语言15.5——C++如何在struct中使用union???

前言

lua底层中对数据结构的实现就是靠struct和union的嵌套实现的,我两个月前开始自制语言时也想这样,但是苦于union使用一直出错,不得已用struct代替了union,这使得解释器浪费了大量的无用内存……


struct中嵌套union解决方法

如果这么嵌套会出现:union xxx 的默认构造函数或者析构函数被删除了,无法使用!!!解决方法很简单,被删除的函数,再定义回来就行!!!!

因为编译器认为那个函数应该被删除,所以你如果不自己定义的话,编译器不会帮你定义,那样自然没法用,要给你抛错误!!!!

测试用例

#include<iostream>
#include<map>
#include <stdlib.h>
#include <stdio.h>
#include<iomanip>
using namespace std;


enum IDType {
    
    
	IDType_nil,				//
	IDType_int,				//int_num
	IDType_number,			//double_num
	IDType_bool,			//flag
	IDType_string,			//str
	IDType_array,			//
	IDType_function			//
};

//被删除的默认构造函数和析构函数必须重新定义才能用
//用explicit是为了参数传递类型不对时出错,使错误不隐藏起来
typedef union _Val {
    
    
	explicit _Val() {
    
     	}
	~_Val(){
    
    }				
	mutable bool flag;
	mutable int int_num;
	mutable double double_num;
	mutable string* str;
}Val;

typedef struct _ID {
    
    
	explicit _ID(){
    
    }
	explicit _ID(bool _flag) {
    
    
		type = IDType_bool;
		val.flag = _flag;
	}
	explicit _ID(int _int_num){
    
    	
		type = IDType_int;
		val.int_num = _int_num;
	}
	explicit _ID(double _double_num) {
    
    
		type = IDType_number;
		val.double_num = _double_num;
	}
	explicit _ID(string _str) {
    
    
		type = IDType_string;
		val.str = new string(_str);
	}
	~_ID() {
    
    }
	IDType type = IDType_nil;
	Val val;
}ID;



std::map<string, ID* >  environment;


void CreateID(string _name) {
    
    
	ID* id = new ID();
	environment[_name] = id;
}

template<typename T>
void CreateID(string _name,T _value) {
    
    
	ID* id = new ID(_value);
	environment[_name] = id;
}





void main() {
    
    

	cout << "bool" << sizeof(bool) << endl;
	cout << "int" << sizeof(int) << endl;
	cout << "double" << sizeof(double) << endl;
	cout << "string" << sizeof(string) << endl;


	CreateID("a");//nil
	CreateID("b",(int)12);//int
	CreateID("c",(double)1213.02);//number
	CreateID("d",(bool)true);//bool
	CreateID("e",(string)"hello world");//string


	for (auto i : environment) {
    
    
		std::cout <<setw(5)<< i.first.c_str() << setw(5) << i.second->type;
		switch (i.second->type) {
    
    
		case IDType_nil:
			cout << setw(8) << "false" << endl;
			break;
		case IDType_int:
			cout << setw(8) << i.second->val.int_num << endl;
			break;
		case	IDType_number:
			cout << setw(8) << i.second->val.double_num << endl;
			break;
		case IDType_bool:
			cout << setw(8) << (i.second->val.flag==1?"true":"false") << endl;
			break;
		case IDType_string:
			cout << setw(8) <<(* i.second->val.str).c_str()  << endl;
			break;
		}
	}
	system("pause");
}
bool1
int4
double8
string28
    a    0   false
    b    1      12
    c    2 1213.02
    d    3    true
    e    4hello world
请按任意键继续. . .

猜你喜欢

转载自blog.csdn.net/weixin_41374099/article/details/105168792