1 / 37

Part I 기본 내용

Part I 기본 내용. Overview. Chapter 2 : 내장 Data Type & Data Type 을 정의하기 위해 알아야 할 Mechanism Chapter 3 : Library Type – String & Vector Chapter 4 : Array Chapter 5 ~ 7 : 표현식 , 문장 , 함수 Chapter 8 : IO Library. Chapter 2. 변수와 기본 Type. Overview. 표준 입출력 객체 기본적인 내장 타입 문자 상수 변수

ordell
Download Presentation

Part I 기본 내용

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. Part I 기본 내용

  2. Overview • Chapter 2 : 내장 Data Type & Data Type을 정의하기 위해 알아야 할 Mechanism • Chapter 3 : Library Type – String & Vector • Chapter 4 : Array • Chapter 5 ~ 7 : 표현식, 문장, 함수 • Chapter 8 : IO Library

  3. Chapter 2. 변수와 기본 Type

  4. Overview • 표준 입출력 객체 • 기본적인 내장 타입 • 문자 상수 • 변수 • const 한정자 • 참조자 • Type 정의 이름 • 열거 Type • Class Type • 자신의 Header File만들기

  5. 표준 입출력 객체 • 입출력 Library : 4객체

  6. 표준 입출력 객체 • IO Library를 사용한 Program #include <iostream> int main() { std::cout << “Enter two numbers :” << std::endl; int v1, v2; std::cin >> v1 >> v2; std::cout << “The sum of “ << v1 << “ and “ << v2 << “ is “ << v1 + v2 << std::endl; return 0; }

  7. Namespace • Namespace & Scope Operator (범위연산자) std::cout std::cin std::endl Namespace Scope Operator

  8. 2.1 기본적인 내장 Type • 산술 Type 집합 • 정수 Type : 정수, 단일문자, Boolean • 부동소수점수 • 문자 Type • char : 시스템 기본 문자 집합 • wchar_t : 중국어, 일본어등의 확장된 문자 집합에 사용 • 정수 Type • short (word크기의 반) • int (word크기) • long (word 크기와 같거나 2배) • bool Type : true(0이 아닌 값), false(=0)

  9. 2.1 기본적인 내장 Type • signed / unsigned type • 부동소수점 수 • float (단정밀도) : 1word(32bits), 유효숫자-6자리 • double (배정밀도) : 2words(64bits), 유효숫자-10자리 • long double (확장정밀도) : 3 or 4 words(96 or 128bits), 유효숫자-10자리

  10. 2.2 문자 상수 (Literal Constant) • 정수 상수 표현 • 10진법 : 20 • 8진법 : 024 • 16진법 : 0x14 • Long type : 128L or 128l • Unsigned : 128U or 128u • Unsigned Long : 128UL • 부동소수점 문자 상수 • 소수점 표기 • 과학적 표기 : 지수 e 또는 E를 사용 • Default : double type • 단정밀도 : F 또는 f를 사용 • 확장정밀도 : L 또는 l을 사용

  11. 2.2 문자 상수 (Literal Constant) • Boolean • true, false • 문자 상수 • char type : ‘a’, ‘2’, ‘.’, ‘ ‘ • wchar_t type : L’a’ • 문자열상수 • 문자의 배열(Array) • “Hello World!”, “A”, L”a wide string literal” • 문자열 결합 std::cout << “A multi-line ” “string literal “ “using concatenation” << std::endl;

  12. 2.2 문자 상수 (Literal Constant) • Escape Sequence

  13. 2.3 변수 (Variables) • 프로그램에서 조작할 수 있는 이름을 가진 공간 • 변수 = 객체 • lvalue (좌변값) • 대입의 왼쪽 또는 오른쪽에 올 수 있는 표현식 • rvalue(우변값) • 대입의오른쪽에만 올 수 있는 표현식 • 변수이름 (식별자) • 문자(Letter), 숫자, 밑줄 : 시작은 문자나 밑줄 문자 • 금지 : 밑줄 문자 두개를 연속해서 쓰거나 밑줄 문자로 시작해 곧바로 대문자 • 금지 : 함수 바깥에서 정의한 식별자는 밑줄 문자로 시작할 수 없다. • 대소문자 구분 • Keyword는 사용할 수 없다. (page79)

  14. 2.3 변수 • 변수 정의(객체 정의) intunits_sold; double sales_price, avg_price; std::string title; Sales_itemcurr_book; • 초기화 (Initialization) • 복사 초기화 (copy-initialization) : 내장 type • intival = 1024; • 직접 초기화 (direct-initialization) : 내장 type, class type • intival(1024)

  15. 2.3 변수 • Class type 초기화 • 초기화 방법을 알려주는 Member 함수 (생성자, constructor)를 정의 • 생성자를 여러 개 정의할 수 있으나, 인자의 수나 type은 달라야 한다. • 예 (string class의 초기화) • std::string titleA = “C++ Primer, 4th Ed.”; • std::string titleB(“C++ Primer, 4th Ed.”); • std::string all_nines(10,’9’); // all_lines = “9999999999” • 기본 생성자(Default Constructor) • 초기값 없이 해당 type의 변수를 정의할 때, 사용되는 생성자 • 변수를 정의한 위치에 관계없이 사용할 수 있다. • 예 : string type의 기본 생성자는 string을 빈 문자열로 초기화 함. • 기본 생성자를 제공하는 않는 class type은 반드시 명시적으로 초기화 해야하며, 초기값 없이 이 type을 정의할 수 없다.

  16. 2.3 변수 • 내장 Type의 초기화 • 함수 본체 밖 : 0으로자동으로 초기화됨. • 함수본체 안 : 초기화 되지 않음. • 선언과 정의 • 정의(Definition) • 변수의 저장 공간을 할당 • 변수에 대한 정의는 하나만 있어야 한다. • 선언(Declaration) • 프로그램에 변수의 Type과 이름을 알린다. • extern 키워드를 사용해 정의 없이 이름만 선언할 수도 있다. (변수의 정의가 다른 곳에 있음을 알림) extern inti; // i를 정의하지 않고 선언 inti; // i를 선언하면서 정의

  17. 주의 • 초기값을 가진 extern : 정의로 간주 extern double pi = 3.1416 • extern 선언은 함수 밖에서 사용할 때만 초기값을 가질 수 있다.

  18. 이름의 사용범위 • 전역 사용 범위 (Global scope) • 함수 밖에서 정의한 이름 • 프로그램 어디서든 접근 가능 • 지역사용 범위 (local scope) • 함수 안에서 정의한 이름 • 함수 안에서만 접근 가능 • 문장 사용 범위 (statement scope) • 문장 내에서 정의하고, 문장 내에서만 접근 • Clsss Scope (chapter 12) • Namespace Scope (chapter 17.2)

  19. 2.4 const 한정자 • Programming의 Tip • 가독성 • 유지 보수성

  20. 2.4 const 한정자 • const type 한정자 • 상수 값을 나타내는 변수 • const로 선언한 객체의 값은 바꿀 수 없으며, 정의할 때 초기화해야 한다. • const 변수를 전역 사용 범위에서 선언하면, 객체를 정의한 파일에 지역적이 된다. – 해당 파일에만 존재, 다른 파일에서는 접근 할 수 없다.  extern을 사용하면, 프로그램 전체에서 const 객체에 접근 가능 // file_1.cc extern const intbufsize = fcn(); // file_2.cc extern const intbufsize; // file_1의 bufsize를 사용 for (int index=0 ; index != bufsize ; ++index) ……..

  21. 2.5 참조자 (Reference) • 참조자 • 객체에 대체 이름을 제공 • &변수이름 • 주로 함수의 매개 변수로 사용 • 독립된 객체로 사용할 경우 같은 type의 객체로 초기화 intival = 1024; int &refVal = ival; int &refVal2; // 오류 : 초기화 int &refVal3 = 10; // 오류 : 초기값=객체 1024 ival refVal

  22. 2.5 참조자 (Reference) • const 참조자 • const 객체를 참조 • 읽을 수는 있지만 기록할 수는 없다. • 일반 참조자는const객체와 결합하지 못한다. • 다른 type의 객체나 문자 상수와 같은 우변 값으로 초기화할 수 있다. inti = 42; const intival=1024; const int &refVal = ival; int &ref2 = ival; //오류 const int &r = 42; // const 참조자만 가능 const int &r2 = r + i;

  23. 2.5 참조자 (Reference) • 다른 type의 객체를 참조 double dval = 3.14; const int &ri = dval; double dval = 3.14; int temp = dval; const int &ri = temp;

  24. 2.6 typedef (Type 정의) 이름 • typedef (Type 정의 ) • type에 대한 동의어를 정의 • Format typedef데이터_type 식별자; typedef double wages; // wages는 double의 동의어 typedefintexam_score; // exam_score는 int의 동의어 typedef wages salary; // double에 대한 간접 동의어 wages hourly, weekly; // double hourly, weekly; exam_scoretest_result; // inttest_result;

  25. 2.7 enumeration(열거)Type • 정수 상수를 정의 + group으로 묶음. • 정의 및 초기화 • enum열거이름열거자(enumerator); enumopen_mode {input, output, append}; // input = 0 // output = 1 // append = 2 • 열거 Type은 const값이다. • 열거 type에 초기값(상수 표현식)을 줄 수 있다. // shape=1, sphere=2, cylinder=3, polygen=4 enum Forms {shape=1, sphere, cylinder, polygen};

  26. 2.7 enumeration(열거)Type • 열거자의 값은 유일한 값이 아니어도 된다. // point2d=2, point2w=3, point3d=3, point3w=4 enum Points {point2d = 2, point2w, point3d=3, point3w}; • 열거 타입 객체는 자신의 열거자중 하나로 초기화하거나 대입할 수 있다. • 같은 열거 타입의 다른 객체를 대입할 수 있다.

  27. 2.7 enumeration(열거)Type // shape=1, sphere=2, cylinder=3, polygen=4 enum Forms {shape=1, sphere, cylinder, polygen}; // point2d=2, point2w=3, point3d=3, point3w=4 enum Points {point2d = 2, point2w, point3d=3, point3w}; Points pt3d = point3d; Points pt2w = 3; // 오류 : pt2w를 int로초기화 pt2w = polygon; // 오류 : polygon은 Points의 열거자가 아님. pt2w = pt3d;

  28. 2.8 Class Type • Class 정의 Data + 객체가 실행할 수 있는 연산 Implementation Interface Interface정의 필요한 data 확정 함수 구현

  29. 2.8 Class Type • Class • Type을 정의 – Class이름과 동일 • Class Type 변수 – 내장 Type과 같은 형식으로 정의

  30. 2.8 Class Type (예제) • 예제 (서점의 책 판매량을 기록한 거래 파일관리) • 거래 내용 : ISBN, 판매부수, 판매가격 • 연산 • 책 별 팔린 판매 부수 • 책 별 총수입 • 평균 판매 가격 • 연산 • 덧셈연산자 (+) : Sales_item을 더함 • 입력연산자 (>>) : Sales_item객체를 읽음 • 출력연산자(<<) : Sales_item객체를 출력함 • 대입연산자 : Sales_item객체 사이에 값을 주고 받음 • Same_isbn : Sales_item이 같은 책을 참조하는지 확인 • Function • 특정 책을 얼마나 많이 팔았는지 기록을 추적한다. • 판매한 책의 총이익을 보고한다. • 판매한 책의 평균 판매 가격을 계산한다.

  31. 2.8 Class Type classSales_item{ public: // Sales_item객체의 연산은 여기에 둔다 private: std::string isbn; unsigned units_sold; double revenue; }; Access Label (접근 레이블) Member Function (멤버함수) Data Member

  32. 2.8 Class Type • 주의 사항 • Class Member는 정의하면서 초기화 할 수 없다. • Member 초기화는 생성자를 통해서 수행 • 접근 Label • 클래스 멤버의 사용여부를 결정 • 멤버 함수는 접근 권한 (Access Lebel)에 관계없이 자신이 속한 Class의 다른 멤버를 사용할 수 있다. • 접근 Label은 클래스 정의에서 여러 번 사용할 수 있다. • 다음 접근 Lebel이 나올때까지 현재 Lebel유지 • public 에 정의된 멤버 : 프로그램 어디서든 접근 가능 (Class 연산) • private 멤버 : Class에 속하지 않는 code는 접근 할 수 없다.

  33. 2.8 Class Type • struct • Class Type을 정의 • 첫번째 접근 Label : public ( class를 사용하면 private ) structSales_item{ // 멤버는 기본적으로 public이므로 public label이 필요 없다. // Sales_item객체의 연산은 여기에 둔다 private: std::string isbn; unsigned units_sold; double revenue; };

  34. 2.8 Class Type (예제) • Sales_item읽고 쓰기 #include <iostream> #include “Sales_item.h” int main() { Sales_item book; // ISBN, 판매부수, 판매가격을 읽는다. std::cin >> book; // ISBN, 판매부수, 총수입, 평균판매가격을출력한다. std::cout << book << std::endl; return 0; }

  35. 2.8 Class Type (예제) • Sales_item더하기 #include <iostream> #include “Sales_item.h” int main() { Sales_item item1, item2; std::cin >> item1 >> item2; // 거래 내용을 2개 읽는다 std::cout << item1 + item2 << std::endl; // 합을 출력한다. return 0; }

  36. 2.9 Header File • Header File • Class 정의 • 컴파일 시점에 값을 알 수 있는 const 객체 정의 • inline함수 정의 • extern 변수 선언 • 함수 선언 • Header File 사용시 이점 • 해당 요소를 사용하는 모든 파일에서 선언이 동일함을 보장 • 선언이 바뀌었을 때 Header만 고치면 됨

  37. 2.9 Header File • 중복 포함 피하기 #ifndef SALESITEM_H #define SALESITEM_H ……. // Sales_item클래스와 관련 홤수 정의 …….. #endif

More Related