C#/C#200제

[C#] 10일차 - 65. 클래스와 구조체

반나무 2021. 1. 30. 14:13

클래스와 구조체는 기본적으로 하나의 논리 단위에 속하는 '데이터' 및 '동작'을 캡슐화하는 데이터 구조입니다.

 

예를들어 하나의 날짜를 표현할때는 년.월,일이 다 필요하기 때문에 다음과 같이 구조체 또는 클래스로 만들어서 사용하는 것이 편리하다.

// 구조체
struct Date
{
    public int year;
    public int month;
    public int day;
}

// 클래스
class Date
{
    public int year;
    public int month;
    public int day;
}

 

사용할 때는 클래스라면 참조형이기 떄문에 반드시 new 키워드를 사용해 만들어야 합니다.

// 구조체
Date birthDay;

// 클래스
Date birthDay = new Date();

 

구조체와 클래스로 만들어지는 변수를 인스턴스, 즉 객체라고 합니다. 위의 예에서 birthDay는 객체입니다.

 

객체의 필드는 birthDay.year 이렇게 접근할 수 있습니다.

 

구조체와 클래스의 생성범위

  1. 클래스 안 -> 그 구조체나 클래스는 자기를  포함하고 있는 클래스안에서만 사용할 수 있음
  2. 같은 파일 안에서 클래스 밖 -> 다른곳에서 사용하기 위해선 같은 프로젝트 안에 있어야함
  3. 다른 파일의 세가지 위치

 

 

일반적으로 클래스는 좀 더 복잡한 동작이나 객체를 만든 후 수정하려는 데이터를 모델링하는데 사용된다.

구조체는 만든 후에 수정하지 않으려는 데이터를 포함하는 작은 데이터 구조에 적합합니다.

 

 

구조체와 클래스 비교정리

  • 구조체와 클래스는 class와 struct 키워드만 뺴고 구문이 똑같다.
  • 구조체는 값형이고 클래스는 참조형이다.
  • 즉 구조체는 메모리의 스택영역에 공간을 갖게되고 클래스는 스택에 참조만 위치하게된다. 클래스는 받스시 new 키워드를 사용해 객체를 생성한다.
  • 구조체와 클래스 모두 세가지 위치에 만들수 있다. 
  • 구조체와 클래스 모두 new 키워드로 만들 수 있는데, 이 경우에는 필드의 값들이 모두 디폴트 값으로 초기화된다.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace A065_ClassAndStruct
{
    struct DateStruct
    {
        public int year, month, day;
    }

    class DateClass
    {
        public int year, month, day;
    }

    class Program
    {
        static void Main(string[] args)
        {
            // 구조체
            DateStruct sDay;
            sDay.year = 2021;
            sDay.month = 1;
            sDay.day = 30;
            Console.WriteLine("구조체와 클래스 사용");
            Console.WriteLine("sday: {0}/{1}/{2}", sDay.year, sDay.month, sDay.day);

            // 클래스
            DateClass cDay = new DateClass();
            cDay.year = 2021;
            cDay.month = 1;
            cDay.day = 30;
            Console.WriteLine("cday: {0}/{1}/{2}", cDay.year, cDay.month, cDay.day);
            Console.WriteLine();



            Console.WriteLine("구조체와 클래스를 초기화");
            // 구조체, 클래스 초기화 값
            DateStruct sDay2 = new DateStruct();
            Console.WriteLine("sDay2: {0}/{1}/{2}", sDay2.year, sDay2.month, sDay2.day);
            
            DateClass cDay2 = new DateClass();
            Console.WriteLine("cDay2: {0}/{1}/{2}", cDay2.year, cDay2.month, cDay2.day);
            Console.WriteLine();

            // 구조체, 클래스를 복사하면?
            DateStruct s = sDay;
            DateClass c = cDay;

            s.year = 2000;
            c.year = 2000;

            Console.WriteLine("구조체와 클래스를 복사하면?");
            Console.WriteLine("s: {0}/{1}/{2}", s.year, s.month, s.day);
            Console.WriteLine("c: {0}/{1}/{2}", c.year, c.month, c.day);
            Console.WriteLine("sDay: {0}/{1}/{2}", sDay.year, sDay.month, sDay.day);
            Console.WriteLine("cDay: {0}/{1}/{2}", cDay.year, cDay.month, cDay.day);



        }
    }
}

반응형