从0学习C++ (三) 结构体中包含共同体

#include <iostream>;
#include <cmath>;
#include <string>;
#include <cstring>;

/*
	结构体中包含共用体
	举例:管理一个商品小目录,其中有一些商品的ID是整数,而另一些的ID是字符串。
	     在这种情况下,可以这样做:
*/
struct widget{
	char brand[20];
	int type;
	union id{
	long id_num;
	char id_char[20];
	}id_val;
};




int main(){

	using namespace std;
	
	widget price;
	price.type = 2;

	if(price.type == 1){
		cin >> price.id_val.id_num;
	}else{
		cin >> price.id_val.id_char;	
	}

	if(price.type == 1){
		cout << price.id_val.id_num << endl;
	}else{
		cout << price.id_val.id_char << endl;
	}

	
	


}

猜你喜欢

转载自android-zhang.iteye.com/blog/1995163