lang:自制編程語言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
請按任意鍵繼續. . .
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章