---
title: "从0学习C++ (三) 结构体中包含共同体"
author: "android_zhang"
date: "2014-01-02T17:48:52Z"
tags: []
categories: ["移动开发"]
slug: "0-c"
draft: false
lastmod: "2013-12-25T10:27:25Z"
id: 1995163
url: "https://android-zhang.iteye.com/blog/1995163"
---

```java

#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;
	}

	
	


}


```