C++ 에는 없고 C#에 있는  this [] 기능의 막강한 기능에 대해 알아보겠습니다.
 
작업을 하다보면 동일한 종류의 데이터를 묶어서 새로운 클래스를 만들어 사용하는 경우가 있는데,
동일한 종류의 데이터를 인덱스 형태의 Property로 사용할수 있습니다.
이 기능은 배열의 인덱스 값만으로 내부 데이터를 set, get 할수 있습니다.

학생 클래스 WATStudent 가 있고,
학생 클래스를 멤버로 사용하는 학생들 클래스 WATStudents 를 예로 들겠습니다.
this[]는 학생번호로 학생클래스를 가져오는데 사용됩니다.
(참고로 this[] 의 이해를 위해 예외 처리부분과 Out of Bounds 등의 처리는 하지 않았습니다.)

C++ 경우
class WATStudent     // 대략 이렇습니다.
{
     CString strName;
     int iScore;  

class WATStudents
{
     class WATStudent student[50] ;  // 대략 이렇습니다.
 
      // 학생 클랙스 얻는 함수
     WATStudent GetStudent(int index){
              return student[index];
      }
     void SetStudent(int index, WATStudent student)
    {
          student[index] = student;
     }
}
 
main()
{
     WATStudents students;

     // 5번째 학생 정보 얻기
     WATStudent oneStudent = students.GetStudent(4);
}
 
C++ 에서는 이와 비슷한 형태를 가질 것입니다.
학생 클래스를 얻기 위해 GetStudent() 메소드가 선언되었고,
학생 클래스를 입력하기 위해 SetStudent() 메소드가 사용되어
2개의 다른 메소드를 만들어 사용해야 합니다.
 
이 형태를 C# 으로 구현해 보겠습니다.
 
 
C#
class WATStudent     // 대략 이렇습니다.
{
     CString strName;
     int iScore;  

 
class WATStudents
{
     class WATStudent student[50] ;  // 대략 이렇습니다.
 
      // 학생 클랙스 얻는 함수
     WATStudent this[int index]{
            get
             {
              return student[index];
             }
            set
             {
              student[index] = value;
             }
      }
}
 
main()
{
     WATStudents students;
 
     // 5번째 학생 정보 얻기
     WATStudent oneStudent = students[4]; 
}
   

C#은 C++에 비해 짧은 코드로 구현 가능하여 가시성이 좋다.

출처 : http://whiteat.com/zbxe/?mid=WhiteAT_Csharp&document_srl=37035

+ Recent posts