C# 구조체와 클래스 설명 1

m._.jooong·2023년 3월 7일
0

Unity C#

목록 보기
13/22
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

// 구조체 (struct)
// 같은 목적을 갖는 여러 데이터형 변수들과 메서드들의 집합
// 구조체 객체는 Value Type 이다.
// 구조체의 주 용도 : 상대적으로 간략한 데이터 값을 저장하는데 사용된다.
// 구조체는 상속 될 수 없다.

// 클래스 (class)
// 같은 목적을 갖는 여러 데이터형 변수들과 메서드들의 집합
// 클래스 객체는 Reference Type 이다.
// 클래스의 주 용도 : 소프트웨어를 부품화(객체지향 프로그래밍)하기 위한 도구로 사용된다.

// Value Type의 변수 : int, float, double, ..., struct(구조체) 객체
// Reference Type의 변수 : 배열, class 객체

// 구조체(struct)
public struct Student  //<-- 구조체 설계
{
    public string m_Name;   //<-- 맴버변수
    public int m_Kor;       //C#에서는 구조체에서 public 속성을 생략하면
    public int m_Eng;       //디폴트 속성은 private 속성이 된다.
    public int m_Math;
    public int m_Total;
    public float m_Avg;

    public void PrintInfo()  //<-- 맴버 메서드 정의
    {
        string str = string.Format("{0} : 국어({1}) 영어({2}) 수학({3}) 총점({4}) 평균({5:#.##})",
                        m_Name, m_Kor, m_Eng, m_Math, m_Total, m_Avg);
        Debug.Log(str);
    }
}

// 클래스 (class)
public class Item   //<-- 클래스 설계
{
    public string m_Name; //아이템 이름  //<-- 맴버 변수
    public int m_Level;   //아이템 레벨
    public int m_Star;    //아이템 성급
    public int m_Price;   //아이템 가격
    float m_AttackRate = 1.0f; //아이템의 공격 상승률 
    //C#에서는 접근수식자를 생략하면 디폴트값은 private 속성이다.
    //protected : 외부에서 접근할 수 없고, 자신과 상속관계의 자식클래스까지는 접근을 허용하는 속성

    public void PrintInfo()  //<-- 맴버 메서드
    {
        string str = string.Format("{0} : 레벨({1}) 성급({2}) 가격({3}) 공격상승률({4:#.##})", 
                        m_Name, m_Level, m_Star, m_Price, m_AttackRate);
        Debug.Log(str);
    }

    public void SetAttRate(float val)
    {
        if (val < 0.0f || 50.0f < val)
            return;

        m_AttackRate = val;
    }
}

public class Test_1 : MonoBehaviour
{
    public Button m_StartBtn;

    // Start is called before the first frame update
    void Start()
    {
        Student AAA = new Student();    //구조체 변수 선언
        AAA.m_Name = "고양이";
        AAA.m_Kor  = 23;
        AAA.m_Eng  = 35;
        AAA.m_Math = 72;
        AAA.m_Total = AAA.m_Kor + AAA.m_Eng + AAA.m_Math;
        AAA.m_Avg = AAA.m_Total / 3.0f;
        AAA.PrintInfo();

        Student BBB = new Student();
        BBB.m_Name = "강아지";

        Student CCC = new Student();
        CCC.m_Name = "드래곤";

        Student a_TestVal = AAA;        //<-- 구조체는 Value Type으로 동작한다.
        //a_TestVal.m_Name = AAA.m_Name;
        //a_TestVal.m_Kor  = AAA.m_Kor;
        //a_TestVal.m_Eng  = AAA.m_Eng;
        //          :
        a_TestVal.m_Name = "아기상어";
        a_TestVal.m_Kor = 99;
        a_TestVal.m_Eng = 99;
        a_TestVal.m_Math = 99;
        a_TestVal.m_Total = a_TestVal.m_Kor + a_TestVal.m_Eng + a_TestVal.m_Math;
        a_TestVal.m_Avg = a_TestVal.m_Total / 3.0f;

        Debug.Log("--- 구조체 Value Type Test ---");
        AAA.PrintInfo();
        a_TestVal.PrintInfo();
        Debug.Log("--- 구조체 Value Type Test ---");


        //클래스 변수 선언
        Item a_MyItem = new Item();     //객체 생성, 인스턴스 생성
        a_MyItem.m_Name = "천사의 검";
        a_MyItem.m_Level = 4;
        a_MyItem.m_Star  = 2;
        a_MyItem.m_Price = 1200;
        //a_MyItem.m_AttackRate = 1.3f; //private 속성은 객체를 통해서 외부에서 접근할 수 없다.
        a_MyItem.SetAttRate(1.3f);
        a_MyItem.PrintInfo();

        Item a_TestRef = a_MyItem;      //<-- 클래스는 Reference Type으로 동작한다.
        a_TestRef.m_Name  = "간달프의 지팡이";
        a_TestRef.m_Level = 99;
        a_TestRef.m_Star  = 99;
        a_TestRef.m_Price = 99;
        a_TestRef.SetAttRate(99.9f);

        Debug.Log("--- 클래스 Reference Type Test ---");
        a_MyItem.PrintInfo();
        a_TestRef.PrintInfo();
        Debug.Log("--- 클래스 Reference Type Test ---");

    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

0개의 댓글