[TIL] 21-08-16

전재우·2021년 8월 16일
0

구조체

#include <iostream>

using namespace std;

int main() {
	//구조체
	//다른 데이터형이 허용되는 데이터의 집합

	//배열 : 같은 데이터형의 집합
	
	//축구선수에 필요한 데이터
	string name;
	string position;
	float height;
	float weight;
	//=> 하나의 집합으로 데이터를 관리하면 편리 할것 같다.
	//--> 구조체

	struct MyStruct
	{
		string name;   // => 멤버 
		string position; 
		float height;
		int weight;
	}B;    //만든 구조체 끝에 B로 선언하여 변수를 바로 생성 가능하다.
	
	MyStruct A;  //A라는 이름의 MyStruct 타입의 변수를 생성
	A.name = "son";
	A.position = "Striker";
	A.height = 183.0;
	A.weight = 88;

	/* 아래와 같이 초기화도 가능하다.
	   MyStruct A = {
		   "Son",
		   "Striker",
		   183,
		   77
	   }
	*/

	B = {

	};//빈 중괄호로 선언하게 된다면 빈값들은 각각 0에 해당되어 저장된다.
	cout << B.height << endl;

	MyStruct C[2] = {//구조체를 배열로 선언 가능하다.
		{"A", "A", 1, 1},
		{"B", "B", 2, 2}
	};

	cout << C[0].height << endl;
	return 0;

}

공용체(union) 열거체 (enum)

#include <iostream>

using namespace std;

int main() {
	//공용체 (Union)
	//서로 다른 데이터형을 한번에 한 가지만 보관할 수 있음.

	union MyUnion
	{
		int intVal;
		long longVal;
		float floatVal;
	};

	MyUnion test;

	test.intVal= 3;
	cout << test.intVal << endl;

	test.longVal = 33;
	cout << test.intVal << endl;
	cout << test.longVal<< endl;
	test.floatVal = 3.3;
	cout << test.intVal << endl;
	cout << test.floatVal << endl;
	cout << test.floatVal << endl;

	//열거체 (enum)
	//기호 상수를 만드는 것에 대한 또다른 방법

	enum spectrum {red,orange,yellow, green, blue, violet, indigo, ultraviolet
	};
	enum spectrum {
		red= 0 , orange = 2, yellow = 4, green, blue, violet, indigo, ultraviolet
	}; 
	//초기화 할떄는 무조건 int형으로 초기화 하고 만약 초기화를 해주지 않으면 맨마지막 초기화된 값에 +1된 값이 적용된다

	//1. spectrum을 새로운 데이터형 이름으로 만듭니다.
	//2. red, orange, yellow... 0부터 7까지 정수 값을 각각 나타내는 기호 상수를 만듭니다.
	//열거자들 끼리의 산술 연산 적용 X
	//int형 변수에 대입할 떄는 산술 연산 적용 가능하다.
	spectrum a = orange;

	int b;
	b = blue;
	b = blue + 3;
	cout << a << endl;
}
profile
코린이

0개의 댓글