728x90
반응형

04. 사용자 지정형 (struct, enum, class, interface)


구조체

  • 형식

public struct 구조체명  // public : 접근지정자
{
    // 멤버, 속성, 메서드
}

 

  • 제한 사항

- 구조체에 선언된 const, static 변수만 초기화 가능하다.

3-15 예제) 구조체 안의 const 또는 static 변수에 대해서만 선언과 동시에 초기화하는 예이다.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication15
{
    public struct MyStruct
    {
        public const float PI = 3.14f;
        public static int Age = 12;
       
    } 
   

    class Program
    {
        static void Main(string[] args)
        {            
            Console.WriteLine("{0} {1}", MyStruct.PI, MyStruct.Age); // 3.14, 12           
        }
    }
}

 

- 구조체 안에 선언할 수 있는 생성자는 매개변수가 반드시 있어야 한다.

3-12 예제) 구조체에 생성자와 소멸자를 명시하고 new로 생성했을 때와 일반 선언 했을 때의

초기화 값을 비교하는 예이다.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication16
{
    public struct MyStruct
    {
        public int Age;
        public MyStruct(int InAge) //int InAge : 매개변수
        {
            Age = InAge;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            MyStruct TestStruct1;
            TestStruct1.Age = 12;
            Console.WriteLine(TestStruct1.Age); // 12

            MyStruct TestStruct2 = new MyStruct();         
            Console.WriteLine(TestStruct2.Age); // 0 // 기본적으로 0으로 셋팅된다.

            MyStruct TestStruct3 = new MyStruct(12);
            Console.WriteLine("{0}", TestStruct3.Age); // 12
        }
    }
}

 

- 구조체를 같은 구조체에 대입하게 되면 값이 복사

예제 3-17)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication18
{
    public struct MyStruct
    {  
        public int Age;       
    }

    class MyClass
    {
        public int Age;
    }

    class Program
    {
        static void Main(string[] args)
        {
            //MyStruct test1 = new MyStruct();
            //test1.Age = 12;
            //MyStruct test2 = test1;
            //test2.Age = 24;
            //Console.WriteLine("{0} {1}", test1.Age, test2.Age); // 12, 24

            MyClass test3 = new MyClass();
            test3.Age = 12;
            MyClass test4 = test3;
            test4.Age = 24;
            Console.WriteLine("{0} {1}", test3.Age, test4.Age);  // 24, 24         
        }
    }
}

- 구조체는 값 형식이고 클래스는 참조 형식이다.

3-18 예제) 구조체의 값 형식과 클래스의 참조 형식을 비교하는 소스를 입력하고 출력을 살펴보자.
그리고 값 형식은 일반 변수와 값으므로 구조체의 값 변화는 다른 구조체에게 영향을 주지 않지만 
참조 형식은 객체를 참조하는 것이므로 서로에게 값의 영향을 준다.

 

- 구조체 

구조체는 값 형식으로 선언만으로도 사용가능

new를 사용했을 때만 -> 생성자가 호출

                            -> 기본값으로 초기화

예제)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication19_0
{
    public struct MyStruct
    {
        public int Age;
        public float Num2;
        public bool IsReady;
    }

    class Program
    {
        static void Main(string[] args)
        {
            MyStruct test = new MyStruct();
            Console.WriteLine("{0} {1} {2}", 
                     test.IsReady, test.Age, test.Num2); // False, 0 ,0
        }
    }
}

 

- 구조체는 구조체 또는 클래스에 상속할 수 없다.

- 구조체는 인터페이스를 상속하여 메서드를 구현할 수 있다.

3-15 예제) 국어, 영어, 수학 점수를 구조체 멤버 변수로 입력하고 Compute() 메서드를 호출하면 평균과 총점이 

계산되도록 하여 프로그래밍하면 다음과 같다.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication15
{
    public struct MyStruct
    {
        public int Kor, Eng, Math, Total;
        public float Average; // 평균

        public void Compute() // Compute 메서드 선언
        {
            Total = Kor + Eng + Math;
            Average = Total / 3.0f;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            MyStruct Test1 = new MyStruct();
            Test1.Kor = 80;
            Test1.Eng = 90;
            Test1.Math = 88;
            Test1.Compute();
            Console.WriteLine("총점 : {0} 평균 : {1:f1}", Test1.Total, Test1.Average);
            // f1: 소수점 첫째짜리   // 총점:258 평균:86.0
        }
    }
}

열거형

  • 상수를 문자열로 대치하여 선언,

  • 상수에 의미부여

  • 형식

enum 열거형 명칭{문자열1, 문자열2}; // 문자열1은 0, 문자열2는 1
enum 열거형 명칭{문자열1 = 상수, 문자열2 = 상수}; // 문자열은 +1로 차례대로 할당된다
//ex) 문자열1 = 10이라면 문자열2 = 11이 된다.
enum 열거형 명칭{문자열1 = 상수, 문자열2};

 

  • 기본은 int형이지만 char 형을 제외한 형식 지정할 수 있다.

enum Days:byte{Sun = 0, Mon,
               Tue, Wed, Thu};

 

  • 열거형 변수가 아닌 변수에 열거형 값을 대입할 때는 데이터형을 명시할 것

3-16 예제) 요일에 대한 열거형 변수를 정수형 변수에 대입하여 출력하여 보자.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication20
{
    enum Days : byte { Sun = 1, Mon, Tue, Wed, Thu, Fri, Sat }; // Mon=2, Tue=3,...

    class Program
    {
        static void Main(string[] args)
        {
            byte nValue = (byte)Days.Mon;
            Days day = Days.Tue;
            Console.WriteLine("{0} {1}", nValue, day); // 2, Tue
        }
    }
}
728x90
반응형

+ Recent posts