본문 바로가기
언어 정리/C++_개념_lib

enum, 구조체

by 알 수 없는 사용자 2024. 1. 16.

 

enum 클래스 사용법

 

#include <iostream>
#include <string>

using namespace std;
typedef typename std::string string;

enum Color {
    COLOR_BLACK = 3,
    COLOR_RED = 4,
    COLOR_BLUE,
    COLOR_GREEN,
};

std::string colorToString(Color color) {
    switch (color) {
        case COLOR_BLACK: return "COLOR_BLACK";
        case COLOR_RED:   return "COLOR_RED";
        case COLOR_BLUE:  return "COLOR_BLUE";
        case COLOR_GREEN: return "COLOR_GREEN";
        default:          return "Unknown Color";
    }
}

int main()
{
    Color myColor = COLOR_BLACK;

    // C++ 에서는 key 를 직접 꺼내올수 없다
    std::cout << "Key: " << colorToString(myColor) << std::endl;
    std::cout << ", Value: " << myColor << std::endl;
    std::cout << ", Value: " << Color::COLOR_BLUE << std::endl;

    return 0;
}

 


구조체

 

사용방법

#include <iostream>
#include <utility> // std::forward를 사용하기 위해 필요함

#include <string>

using namespace std;
typedef typename std::string string;

struct Person{
    double height = 170.0; // 기본값 // 0x8 byte
    float weight = 100.0f; // 기본값 // 0x4 byte
    int age = 25; // 기본값 // 0x4 byte
    string name = "Mr. Incredible"; // 기본값 // 0x32 byte
};

struct A{
    string name = "Mr. Incredible"; // 기본값

};

int main()
{
    /* 일일이 초기화*/
    Person me{175.0, 65.0f, 20, "Jack"};
    me.age = 20;
    me.name = "Jack";
    me.height = 175.0;
    me.weight = 65.0f;

    /* Person 구조체타입의 mom, dad 생성*/
    Person mom{175.0, 65.0f, 20, "Jack"}; // mom은 이렇게 초기화 된다.
    Person dad; // 기본값대로 변수값들이 설정된다.
    Person tmp(me); // me 에 있는값 그대로 tmp 객체에 대입
    cout << sizeof(me) << endl;  // 32 + 4 + 4 + 8 == 48
}

'언어 정리 > C++_개념_lib' 카테고리의 다른 글

vector  (0) 2024.01.16
for-each  (0) 2024.01.16
정적변수, 전역변수  (0) 2024.01.16
this, function return 자료형  (0) 2024.01.16
char , 배열과 포인터 차이  (1) 2024.01.04

댓글