본문 바로가기
코스웨어/15년 스마트컨트롤러

20150617-3번-권오민 - LINQ / 가상함수(virtual)&연산자 오버로딩(+=, [ ], ->)

by 알 수 없는 사용자 2015. 6. 17.
728x90
반응형


요약 및 Code 첨부  


    

S/W(C#) 

 S/W(C++)

 ◉LINQ

  ●LINQ 예제1(436~438)

         LINQ 예제1(436~438).txt

  ●LINQ의 기본(1/4) : FROM

  ●LINQ의 기본(2/4) : WHERE

  ●LINQ의 기본(3/4) : ORDERBY

  ●LINQ의 기본(4/4) : SELECT

  ●LINQ 예제2(439~440)

         LINQ 예제2(439~440).txt

  ●LINQ 예제3(443~444)

         LINQ 예제3(443~444).txt

  ●여러 개의 데이터 원본에 질의하기

         여러 개의 데이터 원본에 질의하기.txt

 ◉성적관리에 LINQ적용하기

         성적관리 LINQ(feat.강상규 선배님).txt

  ●Student class 부분

  ●Main class 부분

  ●DB상식(SQL)

 ◉가상 함수(virtual)

  ●class 포인터와 문제점

         class 포인터.txt

         class 포인터 문제점.txt

  ●virtual

         class 포인터 문제점 해결(virtual).txt

 ◉연산자오버로딩

  ●복합대입연산자( += )

         연산자오버로딩( =연산자,219~220).txt

  ●[ ] 연산자

         연산자오버로딩([ ]연산자,224~229).txt

  ●멤버 참조 연산자( -> )

         연산자오버로딩(화살표 연산자,231~233).txt





C# 



LINQ

LINQ 예제1(436~438)

- Language INtegrated Query의 약어로 C#언어에 통합된 데이터 기능이다.

- Query

    - 데이터에 대해 물어보는 것으로써 기본적으로 다음 내용을 포함한다.

        - From : 어떤 데이터 집합에서 찾을 것인가?

        - Where : 어떤 값의 데이터를 찾을 것인가?

        - Select : 어떤 항목을 추출할 것인가?

- Source Coding


class Profile
    {
        
public string Name
        {
            get;
            set;
        }
        
public int Height
        {
            get;
            set;
        }
        
static void Main(string[] args)
        {
            Profile[] arrProfile 
=  {
                                           
new Profile(){Name = "정우성"Height = 186},

                                           new Profile(){Name = "김태희"Height = 158},

                                           new Profile(){Name = "고현정"Height = 172},

                                           new Profile(){Name = "이문세"Height = 178},

                                           new Profile(){Name = "하동훈"Height = 171},

                                    };
            
//LINQ 사용하지 않은 예
            List<Profile> resProfile = new List<Profile>();
            foreach(Profile profile in arrProfile)
            {
                
if(profile.Height > 175)
                {
                    resProfile.Add(profile);
                }
            }
            
//LINQ 사용한 예
            var profiles = from pro in arrProfile
                           where pro.Height 
< 175
                           orderby pro.Height
                           select pro.Height;


            foreach(Profile profile in resProfile)
            {
                Console.WriteLine(
"Name = {0}, Height = {1}", profile.Name, profile.Height);
            }

            foreach (var pr in profiles)
            {
                Console.WriteLine(
"Name = {0}, Height = {}", pr.Height);
            }
        }
    }

- 결과


●LINQ의 기본(1/4) : FROM

- 모든 LINQ 쿼리식은 반드시 from절로 시작한다.

- 쿼리식의 대상이 될 데이터 원본(Data Source)과 데이터 원본 안에 들어 있는 각 요소 데이터를 

   나타내는 범위 변수(Range Varible)을 지정하는 역할을 한다.

        - 데이터 원본은 반드시 IEnumerable<T> 인터페이스를 상속하는 형식이어야 한다.

        - 범위 변수는 쿼리 변수(Query Variable)이라도고 한다.

                - foreach의 반복 변수를 생각하면 이해가 쉽다.

- foreach(int X in a)에서 X이다.


●LINQ의 기본(2/4) : WHERE

- 필터 역할을 하는 연산자이다.

- from절이 데이터 원본으로부터 뽑아낸 범위 변수의 조건을 매개 변수로 입력해준다.


●LINQ의 기본(3/4) : ORDERBY

- 데이터의 정렬을 수행하는 연산자이다.

- 다른 설정이 없으면 오름차순으로 정렬한다.

        - descending 키워드를 이용하면 내림차순으로 데이터를 정렬한다.


●LINQ의 기본(4/4) : SELECT

- 최종 결과를 추출한다

- LINQ의 결과는 IEnumerable<T>로 반환된다.

        - 이 때 형식 매개 변수 T가 select문에 의해 결정 된다.


●LINQ 예제2(439 ~ 440)

- Source Coding

    class Program
    {
        
static void Main(string[] args)
        {
            
int[] numbers = { 92645378110 };

            var result 
= from n in numbers
                         where n % 
2 == 0
                         orderby n
                         select n;

            foreach(
int n in result)
            {
                Console.WriteLine(
"짝수 : {0}", n);
            }
        }
    }

- 결과



●LINQ 예제3(443 ~ 444)

- Source Coding

class Profile
    {
        
public string Name
        {
            get;
            set;
        }
        
public int Height
        {
            get;
            set;
        }
    }

    
class MainApp
    {
        
static void Main(string[] args)
        {
            Profile[] arrProfile 
=  {
                                           
new Profile(){Name = "정우성", Height = 186},
                                           
new Profile(){Name = "김태희", Height = 158},
                                           
new Profile(){Name = "고현정", Height = 172},
                                           
new Profile(){Name = "이문세", Height = 178},
                                           
new Profile(){Name = "하동훈", Height = 171},
                                    };

            var profiles 
= from profile in arrProfile
                           where profile.Height 
< 175
                           orderby profile.Height
                           select 
new
                           {
                               Name 
= profile.Name,
                               InchHeight 
= profile.Height * 0.393
                           };

            foreach (var profile in profiles)
            {
                Console.WriteLine(
"Name = {0}, Height = {1}", profile.Name, profile.InchHeight);
            }
        }
    }

- 결과


●여러 개의 데이터 원본에 질의하기

- 여러 개의 데이터 원본에 접근하려면 from문을 중첩해서 사용하면 된다.

class Class
    {
        
public string Name
        {
            get;
            set;
        }
        
public int[] Score
        {
            get;
            set;
        }

        
static void Main(string[] args)
        {
            
Class[] arrClass =  {
                                    
new Class(){Name = "연두반"

                                               Score = new int[]{99807024}},
                                    
new Class(){Name = "분홍반"

                                               Score = new int[]{60458772}},
                                    
new Class(){Name = "파랑반"

                                               Score = new int[]{92308594}},
                                    
new Class(){Name = "노랑반"

                                               Score = new int[]{9088017}}
                                };
            var classes 
= from c in arrClass
                            from s in c.Score

                            where s
< 60
                            select new
                            {
                                c.Name, Lowest 
= s
                            };
            foreach(var c in classes)
            {
                Console.WriteLine(
"낙제 : {0} ({1})", c.Name, c.Lowest);
            }
        }
    }

- 결과




◉성적관리에 LINQ 적용하기

- 적용을 다 하지 못해서 부득이하게 강상규 선배님의 자료를 업로드 합니다.


●Student class 부분

     class Student
    {
        string name;

        
public string Name
        {
            get { 
return name; }
            set { name 
= value; }
        }
        
int math;

        
public int Math
        {
            get { 
return math; }
            set 
            {
                
if (value < 0 && value > 100)
                {
                    math 
= 0;
                }
                math 
= value;
            }
        }
        
int science;

        
public int Science
        {
            get { 
return science; }
            set 
            {
                
if (value < 0 && value > 100)
                {
                    science 
= 0;
                }
                science 
= value; 
            }
        }
        
int english;

        
public int English
        {
            get { 
return english; }
            set 
            {
                
if (value < 0 && value>100)
                {
                    english 
= 0;
                }
                english 
= value; 
            }
        }
        
int avg;

        
public int Avg
        {
            get { 
return avg; }
            set { avg 
= value; }
        }
        
public void Show()
        {
            Console.Write(
"{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t", Name, Math, English, Science, (english + math + science), (english + math + science) / 3);
        }       
    }

●Main Class 부분

class Program
    {
        
static void Main(string[] args)
        {
            string name;
            Student std;
            ArrayList arr 
= new ArrayList();
            
            
while (true)
            {
                Console.Write(
"이름을입력하세요..하기싫으면 q : ");
                name
=Console.ReadLine();
                
if(name=="q")
                {
                    
break;
                }
                std 
= new Student();
                std.Name 
= name;
                Console.Write(
"수학점수 : ");
                std.Math 
= int.Parse(Console.ReadLine());
                Console.Write(
"영어점수 : ");
                std.English 
= int.Parse(Console.ReadLine());
                Console.Write(
"과학점수 : ");
                std.Science 
= int.Parse(Console.ReadLine());
                std.Avg 
= (std.Math + std.English + std.Science) / 3;
                arr.Add(std);
                Console.WriteLine(
"입력이완료되었음!!");
            }
            Console.WriteLine(
"출력");
            Console.WriteLine(
" 이름   수학    영어   과학    총점   평균    순위");

            var query 
= from Student student in arr
                        orderby student.Avg descending
                        select student;

            
int c = 1;
            foreach (Student s in query)
            {
                s.Show();
                Console.WriteLine(c);
                c++;
            }

            Console.ReadLine();
            
            
           
        }
    }












- 결과





C++ 


●DB상식(SQL)

- S(structured), Q(query), L(language) : 구조적 질의 언어

- 데이터베이스를 사용할 때, 데이터베이스에 접근할 수 있는 데이터 베이스 하부 언어이다.


◉가상 함수(virtual)

●class 포인터와 문제점

- 천개의 객체를 만들 경우 천개의 class 포인터를 만들어야 하지만 상속을 통해 하나로 class 포인터 

   하나로 처리가 가능하다.

        - class 포인터는 상속된 모든 class를 가리킬 수 있다.

- 하지만 문제가 발생한다.

- 하나의 포인터로 가리킬 수는 있지만, 제어도 되지 않을뿐더러 어떤 것인지 확인도 되지 않는다.



●virtual

- 객체 기반으로 함수를 호출 할 수 있다.

        - 포인터와 상관없이 최종 객체를 대상으로 처리해준다.

                - 객체의 실체를 알고 싶거나 객체 단위로 처리할 때 사용한다.

- 함수의 동적링킹

        - 함수의 연결을 사전에 결정된게 아니라 실행 도중의 상황에 맞게 정해진다.


◉연산자 오버로딩

●복합대입연산자(+=)

- +연산자와 유사하지만, 실제로는 전혀 다르다.

        - 호출한 객체를 직접 변경하기 때문에 const가 아니다.

        - 자기 자신이 피연산자 이므로 임시 객체를 필요로 하지 않는다.


●[ ] 연산자

- [ ] 연산자는 배열에서 첨자 번호로부터 요소를 찾는다.

- 반드시 멤버 함수로만 정의할 수 있으며, 전역 함수로는 정의할 수 없다.


●멤버 참조 연산자(->)

- 참조하는 연산자는 (.)과 (->) 2가지가 있다.

        - 그러나, 객체의 포인터로부터 멤버를 읽는 (->)연산자만 오버로딩 대상이다.

- 원래는 이항 연산자인데 오버로딩을 하게되면 단항 연산자가 된다.

- 전역 함수로는 정의할 수 없고, 클래스의 멤버 함수로만 정의할 수 있다.


수정 및 추가 사항을 댓글로 달아주세요~^^

728x90