1 / 46

2 장 . MFC 기초 클래스

2 장 . MFC 기초 클래스. 유틸리티 클래스를 이용하여 객체 생성법과 사용법을 익힌다 . MFC 에서 C++ 의 업캐스팅이 적용되는 원리를 이해한다 . 배열 , 리스트 , 맵 클래스 동작 원리와 사용법을 익힌다. 실습 환경. MFC 콘솔 응용 프로그램 C/C++ 언어에 대한 지식만 있으면 곧바로 실습 가능 상당수의 MFC 클래스 사용 가능 유틸리티 클래스 , 집합 클래스 , 파일 입출력 클래스 , 데이터베이스 클래스 , 소켓 클래스 , ... 알고리즘 개발 시 유용

loren
Download Presentation

2 장 . MFC 기초 클래스

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 2장. MFC 기초 클래스 유틸리티 클래스를 이용하여 객체 생성법과 사용법을 익힌다. MFC에서 C++의 업캐스팅이 적용되는 원리를 이해한다. 배열, 리스트, 맵 클래스 동작 원리와 사용법을 익힌다. Visual C++ MFC Programming

  2. 실습 환경 • MFC 콘솔 응용 프로그램 • C/C++ 언어에 대한 지식만 있으면 곧바로 실습 가능 • 상당수의 MFC 클래스 사용 가능 • 유틸리티 클래스, 집합 클래스, 파일 입출력 클래스,데이터베이스 클래스, 소켓 클래스, ... • 알고리즘 개발 시 유용 • GUI를 배제한 간편한 프로그래밍 • printf() 등을 이용한 편리한 결과 확인

  3. MFC 콘솔 응용 프로그램 작성 (1) 프로젝트 종류 선택

  4. MFC 콘솔 응용 프로그램 작성 (2) AppWizard 1단계

  5. MFC 콘솔 응용 프로그램 분석 (1) • StdAfx.h, StdAfx.cpp • 미리 컴파일된 헤더 • Console.rc, Resource.h • 리소스 정보 • Console.h, Console.cpp • 구현 코드 예제 프로그램의 파일 구성

  6. MFC 콘솔 응용 프로그램 분석 (2) CWinApp theApp; using namespace std; int _tmain(int argc, TCHAR* argv[], TCHAR* envp[]) { int nRetCode = 0; if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0)) { cerr << _T("Fatal Error: MFC initialization failed") << endl; nRetCode = 1; } else { CString strHello; strHello.LoadString(IDS_HELLO); cout << (LPCTSTR)strHello << endl; } return nRetCode; } Console 예제 코드

  7. MFC 콘솔 응용 프로그램 분석 (3) 문자열 리소스

  8. MFC 콘솔 응용 프로그램 분석 (4) API & MFC 라이브러리 C/C++ 라이브러리 console.h, stdafx.h 컴파일러 console.obj stdafx.obj console.cpp, stdafx.cpp 링커 console.exe resource.h console.rc 리소스 컴파일러 console.res 각종 리소스 (문자열, 아이콘, ...) 실행 파일 생성 과정

  9. API 데이터 타입 (1) 기본형

  10. API 데이터 타입 (2) 구조체

  11. CString 클래스 (1) CString str = "안녕하세요."; cout << (LPCTSTR)str << endl; // 실행 결과는? cout << str << endl; // 실행 결과는? • 특징 • 가변 길이 문자열 지원 • 프로그램 실행 중에 문자열 길이를 자유롭게 변경 가능 • 문자열 최대 길이는 (INT_MAX - 1) • const char * 또는 LPCTSTR 대신 CString 객체를 직접 사용 가능 • 그 밖의 경우에는 CString 객체에 (LPCTSTR) 연산자를 명시적으로 적용하는 것이 바람직함

  12. CString 클래스 (2) CString str1; str1 = "안녕하세요."; CString str2("오늘은"); CString str3(str2); CString str4 = str1 + " " + str2 + " 즐거운 날입니다."; cout << (LPCTSTR)str1 << endl; cout << (LPCTSTR)str2 << endl; cout << (LPCTSTR)str3 << endl; cout << (LPCTSTR)str4 << endl; str4 += " 하하하"; cout << (LPCTSTR)str4 << endl; CString 객체 생성과 초기화

  13. CString 클래스 (3) CString str; str.Format("x=%d, y=%d", 100, 200); MessageBox(NULL, str, "CString::Format() 연습", MB_OK); CString str; str.LoadString(IDS_HELLO); MessageBox(NULL, str, "CString::LoadString() 연습", MB_OK); CString::Format() 함수 CString::LoadString() 함수

  14. CPoint, CRect, CSize 클래스 void SomeFunc(RECT* rect) { ... } RECT r1; CRect r2; SomeFunc(&r1); // OK! SomeFunc(&r2); // OK! (Upcasting) 클래스 정의 업캐스팅

  15. CPoint 클래스 CPoint::CPoint(int x, int y); CPoint pt1(10, 20); POINT pt = {30, 40}; CPoint pt2(pt); cout << pt1.x << " " << pt1.y << endl; cout << pt2.x << " " << pt2.y << endl; pt1.Offset(40, 30); pt2.Offset(20, 10); cout << pt1.x << " " << pt1.y << endl; cout << pt2.x << " " << pt2.y << endl; if(pt1 == pt2) cout << "두 점의 좌표가 같습니다." << endl; else cout << "두 점의 좌표가 다릅니다." << endl; • 생성자 • 사용 예

  16. CRect 클래스 (1) CRect::CRect(int l, int t, int r, int b); int CRect::Width( ); int CRect::Height( ); BOOL CRect::PtInRect(POINT point); • 생성자 • 직사각형의 폭과 높이 • 좌표의 포함 여부 판단

  17. CRect 클래스 (2) CRect rect1; rect1.SetRect(0, 0, 200, 100); CRect rect2(0, 0, 200, 100); if(rect1 == rect2) cout << "두 직사각형의 좌표가 같습니다." << endl; else cout << "두 직사각형의 좌표가 다릅니다." << endl; RECT rect = {100, 100, 300, 200}; CRect rect3(rect); cout << rect3.Width() << " " << rect3.Height() << endl; CPoint pt(200, 150); if(rect3.PtInRect(pt)) cout << "점이 직사각형 내부에 있습니다." << endl; else cout << "점이 직사각형 외부에 있습니다." << endl; 사용 예

  18. CSize 클래스 CSize::CSize(int x, int y); CSize size1(100, 200); SIZE size = {100, 200}; CSize size2(size); cout << size2.cx << " " << size2.cy << endl; if(size1 == size2) cout << "크기가 같습니다." << endl; else cout << "크기가 다릅니다." << endl; • 생성자 • 사용 예

  19. CTime, CTimeSpan 클래스 ※ CTime 클래스와 CTimeSpan 클래스는 내부적으로 시간값을32비트(MFC 7.0부터는 64비트)로 저장 • CTime 클래스 • 절대적인 시간(예를 들면, 현재 시각)을 처리 • CTimeSpan 클래스 • 시간의 차이값을 처리

  20. CTime 클래스 // CTime::GetCurrentTime() 함수를 이용하여 현재 시각을 구한다. CTime theTime; theTime = CTime::GetCurrentTime(); // 여러 가지 형식으로 화면에 출력한다. CString str = theTime.Format("%A, %B %d, %Y"); cout << (LPCTSTR)str << endl; str.Format("현재 시각은 %d시 %d분 %d초입니다.", theTime.GetHour(), theTime.GetMinute(), theTime.GetSecond()); cout << (LPCTSTR)str << endl; 사용 예

  21. CTimeSpan 클래스 // 시간 차를 구한다. CTime startTime = CTime::GetCurrentTime(); Sleep(2000); CTime endTime = CTime::GetCurrentTime(); CTimeSpan elapsedTime = endTime - startTime; CString str; str.Format("%d초가 지났습니다.", elapsedTime.GetTotalSeconds()); cout << (LPCTSTR)str << endl; 사용 예

  22. 배열 클래스 (1) • MFC 배열 클래스 • 배열 인덱스를 잘못 참조하는 경우 오류를 발생시킴 • 배열 크기가 가변적임 • 템플릿 배열 클래스 • afxtempl.h 헤더 파일

  23. 배열 클래스 (2) • 비템플릿 배열 클래스 • afxcoll.h 헤더 파일

  24. 배열 클래스 (3) CUIntArray array; array.SetSize(10); for(i=0; i<10; i++) array[i] = i*10; for(i=0; i<10; i++) cout << array[i] << " "; cout << endl; CStringArray array; array.SetSize(5); for(i=0; i<5; i++){ CString string; string.Format("%d년이 지났습니다.", (i+1)*10); array[i] = string; } for(i=0; i<5; i++) cout << (LPCTSTR)array[i] << endl; 배열 생성과 초기화

  25. 배열 클래스 (4) CUIntArray array; array.SetSize(5); for(i=0; i<5; i++) array[i] = i; /* 배열 원소 삽입 */ array.InsertAt(3, 77); for(i=0; i<array.GetSize(); i++) cout << array[i] << " "; cout << endl; /* 배열 원소 삭제 */ array.RemoveAt(4); for(i=0; i<array.GetSize(); i++) cout << array[i] << " "; cout << endl; 배열 원소 삽입과 삭제

  26. 배열 클래스 (5) #include "stdafx.h" #include "ArrayTest2.h" #include <afxtempl.h> CWinApp theApp; using namespace std; struct Point3D { int x, y, z; Point3D() {} Point3D(int x0, int y0, int z0) { x = x0; y = y0; z = z0; } }; int _tmain(int argc, TCHAR* argv[], TCHAR* envp[]) { int nRetCode = 0; 템플릿 배열 클래스 (1/3)

  27. 배열 클래스 (6) if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0)) { cerr << _T("Fatal Error: MFC initialization failed") << endl; nRetCode = 1; } else { int i; CArray<Point3D, Point3D&> array; array.SetSize(5); for(i=0; i<5; i++){ Point3D pt(i, i*10, i*100); array[i] = pt; } 템플릿 배열 클래스 (2/3)

  28. 배열 클래스 (7) for(i=0; i<5; i++){ Point3D pt = array[i]; cout<<pt.x<<", "<<pt.y<<", "<<pt.z<<endl; } } return nRetCode; } 템플릿 배열 클래스 (3/3)

  29. 리스트 클래스 (1) Head Tail • MFC 리스트 클래스 • 템플릿 리스트 클래스 • afxtempl.h 헤더 파일

  30. 리스트 클래스 (2) • 비템플릿 리스트 클래스 • afxcoll.h 헤더 파일

  31. 리스트 클래스 (3) char *szFruits[] = {"사과", "딸기", "포도", "오렌지", "자두"}; CStringList list; for(int i=0; i<5; i++) list.AddTail(szFruits[i]); 리스트 생성과 초기화

  32. 리스트 클래스 (4) // 리스트 맨 앞에서부터 순환하면서 데이터를 출력한다. POSITION pos = list.GetHeadPosition(); while(pos != NULL){ CString string = list.GetNext(pos); cout << (LPCTSTR)string << " "; } cout << endl; // 리스트 맨 뒤에서부터 순환하면서 데이터를 출력한다. pos = list.GetTailPosition(); while(pos != NULL){ CString string = list.GetPrev(pos); cout << (LPCTSTR)string << " "; } cout << endl; 리스트 순환

  33. 리스트 클래스 (5) pos = list.Find("포도"); list.InsertBefore(pos, "살구"); list.InsertAfter(pos, "바나나"); list.RemoveAt(pos); // 리스트 맨 앞에서부터 순환하면서 데이터를 출력한다. pos = list.GetHeadPosition(); while(pos != NULL){ CString string = list.GetNext(pos); cout << (LPCTSTR)string << " "; } cout << endl; 리스트 항목 삽입과 삭제

  34. 리스트 클래스 (6) #include "stdafx.h" #include "ListTest2.h" #include <afxtempl.h> CWinApp theApp; using namespace std; struct Point3D { int x, y, z; Point3D() {} Point3D(int x0, int y0, int z0) { x = x0; y = y0; z = z0; } }; 템플릿 리스트 클래스 (1/3)

  35. 리스트 클래스 (7) int _tmain(int argc, TCHAR* argv[], TCHAR* envp[]) { int nRetCode = 0; if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0)) { cerr << _T("Fatal Error: MFC initialization failed") << endl; nRetCode = 1; } else { CList<Point3D, Point3D&> list; for(int i=0; i<5; i++) list.AddTail(Point3D(i, i*10, i*100)); 템플릿 리스트 클래스 (2/3)

  36. 리스트 클래스 (8) POSITION pos = list.GetHeadPosition(); while(pos != NULL){ Point3D pt = list.GetNext(pos); cout<<pt.x<<", "<<pt.y<<", "<<pt.z<<endl; } } return nRetCode; } 템플릿 리스트 클래스 (3/3)

  37. 데이터 해시 함수 데이터 맵 클래스 (1) 맵 동작 원리

  38. 데이터 키 데이터 키 데이터 키 데이터 키 데이터 키 데이터 맵 클래스 (2) MFC 맵 구현

  39. 맵 클래스 (3) • 템플릿 맵 클래스 • afxtempl.h 헤더 파일

  40. 맵 클래스 (4) • 비템플릿 맵 클래스 • afxcoll.h 헤더 파일

  41. 맵 클래스 (5) // 맵 객체를 생성하고 초기화한다. CMapStringToString map; map["사과"] = "Apple"; map["딸기"] = "Strawberry"; map["포도"] = "Grape"; map["우유"] = "Milk"; // 특정 키 값을 가진 데이터를 검색한다. CString str; if(map.Lookup("딸기", str)) cout << "딸기 -> " << (LPCTSTR)str << endl; 맵 생성과 초기화 및 검색

  42. 맵 클래스 (6) // 맵을 순환하면서 모든 키와 데이터 값을 출력한다. POSITION pos = map.GetStartPosition(); while(pos != NULL){ CString strKey, strValue; map.GetNextAssoc(pos, strKey, strValue); cout << (LPCTSTR)strKey << " -> " << (LPCTSTR)strValue << endl; } map.RemoveKey("우유"); map["수박"] = "Watermelon"; 맵 순환 맵 데이터 삽입과 삭제

  43. 맵 클래스 (7) CMapStringToString map; // 맵 객체를 생성한다. map.InitHashTable(12007); // 해시 테이블 크기를 12007로 바꾼다. 맵 최적화

  44. 맵 클래스 (8) #include "stdafx.h" #include "MapTest2.h" #include <afxtempl.h> CWinApp theApp; using namespace std; template <> UINT AFXAPI HashKey(CString& str) { LPCTSTR key = (LPCTSTR)str; UINT nHash = 0; while(*key) nHash = (nHash<<5) + nHash + *key++; return nHash; } 템플릿 맵 클래스 (1/3)

  45. 맵 클래스 (9) int _tmain(int argc, TCHAR* argv[], TCHAR* envp[]) { int nRetCode = 0; if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0)) { cerr << _T("Fatal Error: MFC initialization failed") << endl; nRetCode = 1; } else { CMap<CString, CString&, UINT, UINT&> map; map[CString("사과")] = 10; map[CString("딸기")] = 25; map[CString("포도")] = 40; map[CString("수박")] = 15; 템플릿 맵 클래스 (2/3)

  46. 맵 클래스 (10) UINT nCount; if(map.Lookup(CString("수박"), nCount)) cout<<"수박 "<<nCount<<"상자가 남아 있습니다."<<endl; } return nRetCode; } 템플릿 맵 클래스 (3/3)

More Related