C#/C# Concept

[C#] 구조체

군우 2018. 3. 19. 15:25


구조체는 간단한 객체를 만들 때 에 사용하는 형식

클래스와 겅의 동일한 구문을 사용하지만 , 복사 형식이 다르고 클래스보다 제한이 조금 많은편이다

구조체는 상속이 불강

인터페이스를 구현할 수도 없다.

C#의 기본 자료형은 모두 구조체로 정의되어 있다


클래스와 구조체의 차이점

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

2. 클래스 객체는 힙에 저장되고 구조체 객체는  스택에 저장된다.

3. 배정 연산에서 클래스는 참조가 복사되고 구조체는 내용이 복사 된다.

4. 구조체는 상속이 불가능하다.

5. 구조체의 멤버값은 초기 값을 가질 수 없다.



구조체의 선언

1
2
3
4
5
6
7
8
9
struct Point
 
{
 
public int x;
 
public int y;
 
}
cs


이렇게  생성한다. 생성한  구조체는 new를 사용하지않아도 인스턴스를 생성할 수 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
using System;
 
namespace CSStudy_struct
{
    class Program
    {
        static void Main(string[] args)
        {
            Point point; //Point라는 구조체를 사용하기위한 변수
            point.x = 10;
            point.y = 10;
 
            Console.WriteLine(point.x);
            Console.WriteLine(point.y);
        }
    }
    struct Point
    {
        public int x;
        public int y;
    }
}
cs


구조체의 생성자

구조체는 생성자를 생성할 수 있는데  비어 있으면 안된다

1
2
3
4
5
6
7
8
9
10
11
struct Point
    {
        public int x;
        public int y;
        // 구조체의 생성자는 비어있으면 안됨.
        public Point(int x, int y)
        {
            this.x = x;
            this.y = y;
        }
    }
cs


구조체에서는 이렇게 사용할 수 없다. 구조체는 구조체다

하지만 구조체도 이렇게 두면 안되고 초기화를 해줘야한다.

초기화는 생성자에서 하는 형태로 하면 될 듯.



구조체 복사

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
using System;
 
namespace CSStudy_structcopy
{
    class Program
    {
        class PointClass    // 클래스 
        {
            public int x;
            public int y;
 
            public PointClass(int x, int y) // 클래스의생성자
            {
                this.x = x;
                this.y = y;
            }
        }
 
        struct PointStruct  // 구조체[
        {
            public int x;
            public int y;
 
            public PointStruct(int x, int y) // 구조체의생성자
            {
                this.x = x;
                this.y = y;
            }
        }
        static void Main(string[] args)
        {
            // Class
            PointClass pointClassA = new PointClass(1020); //A생성
            PointClass pointClassB = pointClassA; //A 를 가리키는 B생성
 
            pointClassB.x = 100;
            pointClassB.y = 200;
 
            Console.WriteLine("pointClass A : " + pointClassA.x + "," + pointClassA.y);
            Console.WriteLine("pointClass B : " + pointClassB.x + "," + pointClassB.y);
            Console.WriteLine();
 
            //STRUCT
            PointStruct pointStructA = new PointStruct(1020);
            PointStruct pointStructB = pointStructA;
 
            pointStructB.x = 100;
            pointStructB.y = 200;
 
            Console.WriteLine("pointStructA :" + pointStructA.x + "," + pointStructA.y);
            Console.WriteLine("pointStructB :" + pointStructB.x + "," + pointStructB.y);
        }
    }
}
cs

출력화면