본문 바로가기
프로그래밍

2_10. struct (구조체)

by BlueOcean&Shark 2019. 1. 22.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace cshapExTwo13
{
    class Program
    {
        static void Main(string[] args)
        {
            /*
             * 1) struct와 class의 차이
             * 
             * c#에서 struct를 사용하면 value타입을 만들고
             * class를 사용하면 reference타입을 만듬
             * 
             * - struct
             * int, double, float 타입들을 기본타입이라고 하는데, 
             * 기본타입은 struct로 정의된 value타입이다.
             * 
             * value타입은 상속될 수 없으며, 주로 간단한 데이터값을 저장하는데 사용
             * 
             * 
             * - class
             * reference타입은 class를 정의해서 만들고 
             * 상속이 가능하며 조먿 복잡한 데이터와 기능을 정의하는 곳에 많이 사용
             * 
             * 
             * 2) 구조체 
             *   - struct라는 키워드를 이용해서 정의한다.
             *   - 클래스와 같이 메소드, 속성(프로퍼티)등 거의 비슷한 구조를 가지지만
             *     상속은 할 수 없다.
             *   - 클래스와 마찬가지로 인터페이스구현을 할 수 있다.
             *          
             * */
 
            MyPoint myPoint1;
            myPoint1.x = 100;
            myPoint1.y = 200;
            Console.WriteLine(myPoint1.ToString());
 
            MyPoint myPoint2 = new MyPoint(1000,2000);
            Console.WriteLine(myPoint2.ToString());
 
            // 구조체는 value타입이므로 깊은복사가 된다
            MyPoint myPoint3 = myPoint2;            
            myPoint3.x = 1001;
            myPoint3.y = 2002;
            Console.WriteLine(myPoint3.ToString());
        }
    }
 
    struct MyPoint
    {
        public int x;
        public int y;
 
        // 구조체는 매개변수가 없는 생성자는 선언할 수 없다
        public MyPoint(int _x, int _y)
        {
            this.x = _x;
            this.y = _y;
        }
 
        // 모든 구조체는 System.Object형식을 상속하는 System.ValueType으로부터 직접 상속받음
        //System.Object(부모의부모) - System.ValueType(부모) - struct MyPoint(자식)
        public override string ToString()
        {
            return string.Format($"{x}, {y}");
        }
    }
}
 
cs

----------------------------------결과창-----------------------------------------------

100, 200

1000, 2000

1001, 2002

'프로그래밍' 카테고리의 다른 글

2_12. 인터페이스  (0) 2019.01.27
2_11. Tuple(튜플)  (0) 2019.01.22
2_9. virtual / override / new  (0) 2019.01.22
2_8. is연산자 와 as 연산자  (0) 2019.01.21
2_7.상속관계에서 클래스간의 형변환  (0) 2019.01.21

댓글