3. 기본적인 자료형 (Data Type) 변수(variable): 자료를 저장하는 기억장소 - 모든 변수는 자료형이 지정되어 있어야 하고, 한번 지정된 자료형은 변할 수 없다. - 변수를 사용하기 전에 변수를 미리 정의해야 한다. 자료형_이름 변수리스트; 자료형_이름: 정수형: int, short int, long, unsigned int, … 실수형: float, double, … 문자형: char 부울형: bool, … 연산자 sizeof - 자료형의 크기 예 sizeof(int)
4. 변수의 이름에대한규칙 중복된 이름의 변수를 사용할 수 없다. 변수 이름에는 알파벳, 숫자, 언더스코어(_)만 포함할 수 있다. 단, 숫자는 변수 이름의 첫 번째 글자로 사용할 수 없다. 변수 이름의 길이에는 제한이 없다. 변수 이름에 포함하는 알파벳은 대소문자를 구분한다. 키워드는 변수의 이름으로 사용할 수 없다.
5. 변수의 이름을 붙일 경우 변수의 용도에 맞는 이름 예: StudentsNumber 변수내의 단어와 단어는 구분 예: StudentsNumber, student_number 필요 없이 긴 이름은 피함
7. 정수 타입 (Integers) 정수 타입별로 보관할 수 있는 값의 범위 10 진수, 8 진수, 16 진수의 표현 * 32비트 윈도우즈 시스템을 기준으로 한 값 int decimal = 41; // 10 진수 int octal = 041; // 8 진수 int hexadecimal = 0x41; // 16 진수
9. 문자 타입 (Characters) 문자 타입별로 보관할 수 있는 값의 범위 문자 타입도 결국은 숫자를 보관한다. * 32비트 윈도우즈 시스템을 기준으로 한 값
10. 부울 타입 (Boolean) 부울 타입은 true 혹은 false의 값을 갖는다. bool b1; bool b2; b1 = true; b2 = false; cout << “b1 = “ << b1 << “”; cout << “b2 = “ << b2 << “”;
11. 형 변환 내부적 형 변환 암시적 형변환은 변수에 대한 처리 과정에서 자동적으로 발생하는 형변환이다. 이 때 값이 변할 수 있다. 예: 실수 타입에서 정수 타입으로 형변환 발생 시 소수점 이하 부분이 잘린다. (반올림 아님) 강제 형 변환 1) (type) expression 예 float f = 66.89; int i = (int)f; // i는 66 이 된다. 2) static_cast <자료형 이름>(수식) 예: int n = static_cast<int>(y+0.5);
12. 상수 Define - 매크로 예) #define pi 3.14 const 자료형이름 상수이름 = 초기값; 예) const double pi = 3.14;
14. 논리 연산자 (Logical Operators) 논리 연산을 수행한다. bool b1 = true; bool b2 = false; bool and = b1 && b2; bool or = b1 || b2; bool not = ! b1; * NOT 연산자는 피연산자를 하나만 받는다.
15. 관계연산자와 논리연산자 일반적으로 논리연산자는 관계연산자와 함께 사용한다. 관계연산자의 우선순위가 높으므로 먼저 수행된다. int age = 20; // 나이 bool male = true; // 성별 // 20세 이상이면서 남성인지 여부를 알아봄 bool ok = age >= 20 && male == true
20. 제어구조 판단 구조 if if /else 반복 구조 for While do while
21. if 문 문법 if (조건) 문장 조건: 1. 관계식 식1 관계연산자 식2 관계 연산자:>, >= , <, <=, ==, != 2. 논리식 식1 && 식2, 식1 and 식2 식1 || 식2, 식1 or 식2 ! 식, not 식 블록 여러 개의 문장들을 하나의 단위로 간주 { } 안에 둔다. 조건 문장
22. if 문의 조건 조건의 예 (1) 관계식 a != 0 a > b b*b > 4*a*c (2) 논리식 a > b and b > c a != 0 && b*b > 4*a*c !more // bool more;
23. 시작 x, y,z x<y xy y<z yz x<y xy x,y,z 출력 끝 if 문 예: 세 수를 입력하여 크기 순서대로 출력 #include <iostream> using namespace std; int main() { int x, y, z; cin >> x >> y >> z; int temp; if (x < y) { temp = x; x = y; y = temp; } if (y < z) { temp = y; y = z; z = temp;} if (x < y) { temp = x; x = y; y = temp;} cout << “정렬 결과: “ << x << ““ << y << ““ << z << endl; return 0; }
24. if/else 문 문법 if (조건) 문장1 else 문장2 문제: 세수를 입력하여 최대값을 출력하는 프로그램을 작성하시오 조건 참 거짓 문장1 문장2
25. if/else if …문 문법 if (조건1) 문장1 else if (조건2) 문장2 else if (조건3) …. else if (조건n) 문장n else 문장0 참 조건1 문장1 거짓 참 조건2 문장2 거짓 참 조건3 문장3 거짓 참 조건n 문장n 거짓 문장0
26. switch/case를 사용한 조건 비교 … int grade; level = score / 10; switch( level ) { case 10: case 9: cout << " 학점: A"; break; case 8: cout << " 학점: B"; break; case 7: cout << " 학점: C"; break; case 6: cout << " 학점: D"; break; default: cout << " 학점: D"; break; }
27. exp1 ? exp2 : exp3 int a = 3; int b = 5; int c = a > b ? a : b; Dangling(매달린) else if 문 안에 if 문이 중첩(nested)되어있을 경우, else 문이 if 문의개수와 같지 않을 때 이 else를 어느 if 와 대응? => 가장 가까운 if와 대응시킴 예: if(a > b) if (a > c) x = 10; else x = 20;
30. for 문 for(문장1; 조건; 문장2) 문장3; 문장1 –반복시작 전 초기화 조건 –반복 조건 문장3 - 반복 몸체 문장4 –조건과 관련된 문장으로, 몸체(문장3)를 수행한 후, 마지막에 수행 횟수만큼 반복할 때 주로 사용 예 for(i=1; i <=N; i++) 문장 문장1 참 조건 문장3 거짓 문장2
31. for 문 시작 N 예 N을 입력받아 N!을 출력하는 프로그램을 작성하라. product =1; i = 1; #include <iostream> using namespace std; int main() { int N; int i, product; cin >> N; product = 1; for(i = 1; i <= N; i++) product = product * i // product *= i; cout << N << “! = ” << product << endl; return 0; } 참 i <= N product= product * i 거짓 i++; product를 출력 끝
32. 루프 안에서의 break 루프(while, for)나 switch 블록 안에서 break 를 사용하면 블록 밖으로 실행의 흐름이 이동된다.
33. 반복문 안에서의 continue continue는 루프의 나머지 부분을 무시하고 조건을 반복문의 조건을 점검하는 곳으로 점프하여 루프의 다음을 실행하도록 하는 명령어 예: void main() { int i; for (i=1;i<=50;i++) { if (i % 9 == 0) continue; if (i % 3 == 0) printf("%d",i); } }
34. 연속된 입력값의 처리 –표식을 이용 1) 입력의 마지막 값으로 입력으로 올 수 없는 값(표식: sentinel)을 사용 While loop 사용 성적들을 입력하여 평균을 구하는 프로그램을 작성하라. 성적들을 입력하여 최고성적과 최저성적을 구하는 프로그램을 작성하라. #include <iostream> using namespace std; int main() { int score; int n = 0; float sum = 0, avr; cin >> score; wihle (score != -1) // 표식값: -1 { sum = sum + score; n++; cin >> score; } avr = sum/n; cout << “average = “ << avr << endl; return 0; }
35. 연속된 입력값의 처리–자료개수를 이용 1) 입력자료의 개수를 처음에 입력 for loop 사용 성적들을 입력하여 평균을 구하는 프로그램을 작성하라. 성적들을 입력하여 최고성적과 최저성적을 구하는 프로그램을 작성하라. #include <iostream> using namespace std; int main() { int score; int n, i; float sum = 0, avr; cin >> n; for (i = 0; i <n; i++) { cin >> score; sum = sum + score; } avr = sum/n; cout << “average = “ << avr << endl; return 0; }
37. 배열 의미 배열은 연속적인 항목들이 동일한 크기로 메모리에 저장되는 구조로 그 사용이 간편 배열은 동일한 자료 유형이 여러 개 필요한 경우에 이용할 수 있는 자료 구조 크기 배열의 선언은 다음과 같은 구문을 이용 주요 요소는 배열 변수명(이름), 자료형, 그리고 배열의 크기 배열이름 score 로 정수 int 형의 저장 공간이 메모리에 연속적으로 할당된다.
38. 배열 선언 Declaration of an array: type arrayName[ arraySize ]; Example int c[12]; arraySize must be an integer constant greater than zero. type specify the types of data values to be stored in the array: can be int, float, double, char, etc. 38
39. 배열의원소(Elements of An Array) 배열의특정한 원소(혹은 위치)를 참조하려면 다음을 명시하여야 함 Name of the array (배열 이름) Index of the element (원소 인덱스) : 0 이상 값의 정수 혹은 정수 수식 첫 번째 원소의 인덱스는 0 Example C[0] += 2; C[a + b] = 3; 39
40. Example 40 An array c has 12 elements ( c[0], c[1], … c[11] ); the value of c[0] is –45.
41. 배열 초기화 – 초기화 리스트 이용 Initializer list: items enclosed in braces ({}) and separated by commas. Examples int n[ 5 ] = { 10, 20, 30, 40, 50}; int m[ 5 ] = { 10, 20, 30}; The remaining elements are initialized to zero. int p[ ] = { 10, 20, 30, 40, 50}; Because array size is omitted in the declaration, the compiler determines the size of the array based on the size of the initializer list. 41
42. 배열 초기화 – 루프 이용 Using a loop to initialize the array’s elements Declare array, specify number of elements Use repetition statement to loop for each element Example: int n[10]; for ( int i = 0; i < 10; i++) { n[ i ] = 0; } 42
43. 배열 이용 Usually use for loop to access each element of an array. C++ has no array boundary checking Referring to an element outside the array bounds is an execution-time logic error. It is not a syntax error. You need to provide correct index. 43
44. 배열 이용 – Example 1 Example: 배열 원소들의 합 const int arraySize = 6; int a [ arraySize ] = { 87, 69, 45, 45, 43, 21 }; int total = 0; // need to initialize it!!! for ( int i = 0; i < arraySize; i++) { total += a[i]; } cout <<“Total of array elements is ” <<total<<endl; 44
46. 46 구조체 구조체(structure) 여러 개의 자료형의 값들의 모임을 나타내는 자료형 예: 여러 사람의 학번, 이름, 학과를 저장하는 변수 선언 구조체를 사용하지 않은 경우 int id1, id2, id3; … 학번 char name1[10], name2[10], name3[10]; … 이름 int dept1, dept2, dept3; … 학과코드 구조체를 사용한 경우 struct student { … 구조체 정의 int id; … 학번 char name[10]; … 이름 int dept; … 학과코드 }; struct student p1, p2, p3; … 구조체 변수 선언
47. 47 구조체 정의 구조체의 사용 구조체를 사용하기 위해서는 먼저 구조체의 자료 구조를 정의한다. 그 다음에 정의된 구조체의 자료형을 갖는 변수를 선언한다. 구조체 정의 struct student { int id; … 학번 char name[10]; … 이름 int dept; … 학과코드 } ; student 구조체이름, 태그 이름 id, name, dept 구조체 원소, 필드(field), 멤버(member) 빠뜨리지 않도록 주의
48. 48 구조체 변수 선언 구조체 정의 후 변수 선언 struct student person; struct student p1, p2; 구조체 정의와 함께 변수 선언 struct student { int id; char name[10]; int dept; } p1, p2;
49. 49 구조체 정의와 변수 선언과의 관계 구조체 정의 구조체 변수 선언 id p1 struct student name id dept name p2 dept id name 자료구조 정의 dept 기억장소 할당
50. 50 구조체 멤버 접근 구조체 멤버 접근: 구조체변수.멤버이름 (멤버연산자 .) person.id person.name person.dept p1.id p1.name p1.dept 예 person.id = 20030134; … 학번 초기화 cin >> person.dept ; … 학과코드 입력 예: 두 점 사이의 거리 계산 2차원 좌표를 구조체를 사용하여 나타냄 #include <iostream> #include <cmath> using namespace std; struct point { /* 2차원 좌표 */ float x; float y; };
51. 51 예제 (계속) main() { struct point a, b; /* 두 점을 위한 변수 */ float dx, dy, distance; a.x = 10.0; a.y = 5.0; /* 첫 번째 점의 좌표 초기화 */ cin>> b.x >> b.y; /* 두 번째 점의 좌표 입력 */ dx = a.x - b.x; /* 두 점의 x좌표의 차이 */ dy = a.y - b.y; /* 두 점의 y좌표의 차이 */ distance = sqrt(dx*dx + dy*dy); /* 두 점 사이의 거리 */ cout <<"distance = “ << distance; }
52. 52 중첩된 구조체 중첩된 구조체 구조체의 멤버로서 다른 구조체를 사용할 수 있음 struct triangle { struct triangle { struct point a; 또는 struct point a, b, c; struct point b; }; struct point c; }; 멤버의 접근 struct triangle p; p.a.x = 0; p.a.y = 10; … 구조체 멤버 접근 방법을 … 반복하여 적용
57. 프로그래밍에서의 함수 왜 함수를 사용하는가? 프로그래밍 설계 전략 Divide-and-Conquer 어떤 문제를 해결하기 위해 여러 개의 작은 문제로 쪼개는 것. 사람이 일을 처리하는 방법도 비슷 프로그램의 작성이 용이 반복적인 일을 수행하는 경우 원시파일의 크기를 줄일 수 있음.
58. 함수 유형 라이브러리 함수 라이브러리 함수는 이미 정의되어 있고 컴파일되어 있음 표준 라이브러리 헤더 파일에서 원형을 제공 함수의 원형(prototype)에 맞게 호출 사용자 정의 함수 사용자가 직접 함수 작성 main도 사용자 정의 함수
68. 함수작성 예 Task: write ExchangeValue function that exchange the value of two parameters, both integers int x=10, y=20; Exchange(x,y); cout <<“x=“<<x<<endl; cout << “y=“<<y<<endl; 63 Should print out: x=20 y=10
69. C/C++ function void ExchangeValue(int a, int b) { inttmp; tmp=a; a=b; b=tmp; } void main( ) { int myInteger1=4; int myInteger2=5; ExchangeValue(myInteger1,myInteger2); cout<<“integer1= “<<myInteger1<<endl<<“integer2=“<<myInteger2<<endl; } 64 a,b: formal parameters 올바르게 동작하느냐? Call by value: A copy of the value of myInterger1 and myInterger2 are passed to ExchangeValue. actual parameters
70. C++ Tips 65 CALLING BLOCK FUNCTION CALLED Pass-by-value sends a copyof the value of the actual parameter SO, the actual parameter cannot be changed by the function
71. C++ Tips 66 CALLING BLOCK FUNCTION CALLED Pass-by-reference sends the location (memory address) of the actual parameter the actual parameter can be changed by the function
72. Call-by-reference Good for performance reason: eliminate copying overhead Called the same way as call-by-value int squareByValue (int x); int squareByReference (int & x); int x,z; … squareByValue(x); squareByReference(z); Bad for security: called function can corrupt caller’s data Solution: use const quantifier 67
73. C/C++ function: call by reference void ExchangeValue(int & a, int & b) { inttmp; tmp=a; a=b; b=tmp; } int main(intargc, char ** argv) { int value1=4; int value2=5; int result=ExchangeValue(value1,vaule2); cout<<“value= “<<value1<<endl<<“value2=“<<value2<<endl; } 68 a,b: formal parameters 제대로동작함! actual parameters
74. Passing Arrays as Parameters In C/C++, arrays are always passed by reference & is not used in the formal parameter type. Whenever an array is passed as a parameter, its base address is sent to called function Example: // prototype float SumValues (float values [], int numOfValues ); 69
75. constarray parameter If the function is not supposed to change the array: you can protect the array from unintentional changes, use const in formal parameter list and function prototype. FOR EXAMPLE . . . // prototype float SumValues( const float values[ ], int numOfValues ); 70 If there is statement inside SumValues() that changes values of values array, compiler will report error.
76. // Pre: values[0] through values[numOfValues-1] // have been assigned// Returns the sum of values[0] through// values[numOfValues-1] float SumValues(constfloat values[ ], int numOfValues ) { float sum = 0; for ( int index = 0; index < numOfValues; index++ ) { sum += values [ index ] ; } return sum; } 71
78. Pointer Variable A variable whose value is the address of a location in memory i.e., a variable that points to some address in memory… type * pointer_variable_name; 73 int* intPointer
79. Assign Value to Pointer 74 int alpha; int* intPointer; intPointer = α If alpha is at address 33, memory looks like this alpha
80. Pointer Types 75 2000 12 x 3000 2000 ptr int x; x = 12; int* ptr; ptr = &x; Because ptr holds the address of x, we say that ptr “points to” x
81. Pointer: Dereference Operator (*) An operator that, when applied to a pointer variable, denotes the variable to which the pointer points 76 2000 12 x 3000 2000 ptr int x; x = 12; int* ptr; ptr = &x; std::cout << *ptr; *ptr is the value in the place to which ptr points
82. 77 Pointer: Dereference Operator (*) 2000 12 5 x 3000 2000 ptr int x; x = 12; int* ptr; ptr = &x; *ptr = 5; // changes the value // at adddress ptr to 5
83. Pointer Types 78 char ch; ch = ‘A’; char* q; q = &ch; *q = ‘Z’; char* p; p = q; // the right side has value 4000 // now p and q both point to ch 4000 A Z ch 5000 6000 4000 4000 q p
84. 79 intPtr money Pointer Types All pointer variables should be initialized to be NULL A pointer that points to nothing; available in <cstdlib> NULL is defined to be 0; But NULL is not memory address 0 int * intPtr = NULL; Float * money = NULL;
85. Review: lifetime of variables or objects Global variables/objects: start from before the program starts until main() ends int num; main(){ …. } Local variables/objects: declared within the body of a function or a block Created upon entering the function/block, destroyed upon exiting the function/block Dynamical variables/objects: created using new(), malloc() calls Remains alive until delete() is called to free the memory Destroyed upon the program exits 80
86. Dynamic allocation (new operator) Allocation of memory space for a variable at run time (as opposed to static allocation at compile time) 81 int * intPointer; intPointer = new int;
87. Deallocate allocated memory Dynamically allocated memory needs to be deallocated when it’s no more used Otherwise, memory leak will degrade performance delete operator returns memory to system delete p; Value of p is unchanged, i.e. pointing to a deallocated memory Accessing a deallocated memory (*p) can be dangerous Always set to NULL after deallocation delete p; // free up memory pointed to by p p = NULL; // safeguard, extremely important 82
88. Pointers: examples Figure 4-3(a) Declaring pointer variables; (b) pointing to statically allocated memory; (c) assigning a value; (d) allocating memory dynamically; (e) assigning a value 83
90. Dynamically Allocated Arrays Use new operator to allocate an array dynamically int arraySize; //ask user to enter arraySize… // double *anArray = new double[arraySize]; arraySize has a value determined at run time Dynamically allocated array can be increased double *oldArray = anArray; anArray = newdouble[2*arraySize]; // copy from oldArray to anArray delete [] oldArray; // deallocate oldArray 85
92. Let’s focus on: Data Data: the representation of information in a manner suitable for communication or analysis by humans or machines Data are the nouns of the programming world: The objects that are manipulated The information that is processed Different view about data Application view: what real life object can be modeled using the data ? Logic view: how to use the data ? Operations ? Implementation view: how to implement the data ? 87
93. 88 Address pointer reference C++ Built-In Data Types Simple Composite Integral Floating array struct union class char short int long enum float double long double
94. Using C/C++ Data Type As a C/C++ programmer, we know Based on the application, we model them as different “variables” Age: integer Gender: enumeration Name: array of char, or string Also we know what kind of operations each data type supports We do not worry about how an integer is implemented Unless in computer organization class … 89
95. C++ programmer are user of int 90 TYPE int Representation of int as 16 bits two’s complement + Implementation of Operations Value range: INT_MIN . . INT_MAX Operations: + prefix - prefix + infix - infix * infix / infix % infix Relational Operators infix (inside)
96. Different Views of Data Application (or user) levelmodeling real-life data in a specific context When to use a certain data type ? Logical (or ADT) levelabstract view of the domain and operations What How to use the data type ? Implementation levelspecific representation of the structure to hold the data items, and the coding for operations How to implement the data type ? 91
97. Different Views of Data: Library Example Application (or user) levelLibrary of Congress, or Baltimore County Public Library A library system can be implemented for Library of Congress… Logical (or ADT) leveldomain is a collection of books; operations include: check book out, check book in, pay fine, reserve a book A library’s necessary functions to outside world Implementation levelrepresentation of the structure to hold the “books” and the coding for operations How a specific library is implemented (how are books organized…)? 92
98. A two-dimensional array A structured composite data type made up of a finite, fixed size collection of homogeneous elementsordered in two dimensions and for which direct access is provided: dataTable[row][col] 93 Logic view of 2D array:all a C++ program needs to know logical level int dataTable[10][6];
99. Many recurrent data types List Queue: First In First Out Operating System: process queues, printing job queue Stack: Last in First out Calling stack Compiler: to parse expressions Graph: Model computer network …. 94 Provide a high-level data type with these logic property
100. Data Abstraction: the idea Data Abstraction: the separation of a data type’s logical properties from its implementation User of the data type only needs to understand its logical property, no need to worry about its implementation 95 LOGICAL PROPERTIES IMPLEMENTATION What are the possible values? How can this be done in C++? What operations will be needed?
101. Abstract Data Type: A logic view Abstract Data Type is a specification of a set of data the set of operations that can be performed on the data Constructors: to creates new instances of an ADT; usually a language feature Transformers (mutators): operations that change the state of one or more data values in an ADT Observers: operations that allow us to observe the state of the ADT Iterators: operations that allow us to access each member of a data structure sequentially Abstract Data Type is implementation independent 96
102. OOP & ADT Object-oriented language provide mechanism for specifying ADT and implementing ADT Class An unstructured type that encapsulates a fixed number of data components (data members) with the functions (member functions) that manipulate them predefined operations on an instance of a class are whole assignment and component access Client Software that uses (declares and manipulates) objects (instances) of a particular class to solve some problem 97
103. Object-Oriented Programming: Basics Class an unstructured type that encapsulates a fixed number of data components (data members) with the functions (called member functions) that manipulate them Object An instance of a class Method A public member function of a class Instance variable (Data Member) A private data member of a class 98
104. Higher-Level Abstraction Class specification A specification of the class members (data and functions) with their types and/or parameters Class implementation The code that implements the class functions 99 Why would you want to put them in separate files?
105. Classes vs. Structs Without using public and private, member functions and data are private by default in classes public by default in structs. Usually, there is no member functions defined in structs struct is passive data class is active data 100
106. classDateType Specification // SPECIFICATION FILE ( datetype.h ) class DateType// declares a class data type { public : // 4 public member functions DateType (int newMonth,int newDay,int newYear);//constructor int getYear( ) const ; // returns year int getMonth( ) const ; // returns month int getDay( ) const ; // returns day private : // 3 private data members int year ; int month ; int day ; } ; 101 101
107. Use of C++ data type class Variables of a class type are called objects (or instances) of that particular class. Software that declares and uses objects of the class is called a client. Client code uses public member functions (called methods in OOP) to handle its class objects. Sending a message means calling a public member function. 102
108. Client Code Using DateType #include “datetype.h” //includes specification of the class #include <iostream> using namespace std; int main ( ) { // declares two objects of DateType DateType startDate ( 6, 30, 1998 ) ; DateType endDate ( 10, 31, 2002 ) ; bool retired = false ; cout << startDate.getMonth( )<< “/” << startDate.getDay( ) << “/” << startDate.getYear( ) << endl; while ( ! retired ) { finishSomeTask( ) ; . . . } return 0; } 103 How to dynamically create a DateType object ? 103
109. 2 separate files for class type // SPECIFICATION FILE ( datetype .h ) // Specifies the data and function members. class DateType { public: . . . private: . . . } ; // IMPLEMENTATION FILE ( datetype.cpp ) // Implements the DateType member functions. . . . 104
110. Implementation of member functions // IMPLEMENTATION FILE (datetype.cpp) #include “datetype.h” // also must appear in client code DateType :: DateType ( int newMonth, int newDay, int newYear ) // Post: year is set to newYear. // month is set to newMonth. // day is set to newDay. { year = newYear ; month = newMonth ; day = newDay ; } 105 :: Scope resolution operator 105
111. C++ Classes: Constructors Invoked/called (automatically) when an object of the class is declared/created A class can have several constructors A default constructor has no arguments different constructors with different parameter list (signature) Eg. DateType can be extended to have the following constructor : DateType (int secondsSinceEpoch); The compiler will generate a default constructor if you do not define any constructors 106
112. int DateType :: getMonth ( ) const // Accessor function for data member month { return month ; } int DateType :: getYear ( ) const // Accessor function for data member year { return year ; } int DateType :: getDay ( ) const // Accessor function for data member day { return day ; } 107 107
113. C++ Classes: Destructors* Called (automatically) when an object’s lifetime ends To free up resources taken by the object, esp. memory Each class has one destructor If you don’t need to free up resources, you can omit define destructor and the compiler will generate a default destructor 108
114. C++ Namespaces* A mechanism for logically grouping declarations and definitions into a common declarative region namespace myNamespace { // Definitions // Declarations . . . } //end myNamespace The contents of the namespace can be accessed by code inside or outside the namespace Use the scope resolution operator (::) to access elements from outside the namespace Alternatively, the using declaration allows the names of the elements to be used directly 109
115. C++ Namespace: simple example* Creating a namespace namespace smallNamespace { int count = 0; void abc(); } // end smallNamespace Using a namespace smallNamesapce::count=0; usingnamespace smallNamespace; count +=1; abc(); 110
116. C++ std namespace* Items declared in the C++ Standard Library are declared in the std namespace You include files for several functions declared in the std namespace To include input and output functions from the C++ library, write #include <iostream> usingnamespace std; 111
117. Encapsulation Just as a capsule protects its contents, the class construct protects its data members 112 // SPECIFICATION FILE ( datetype.h ) class DateType { Public : DateType (int newMonth,int newDay,int newYear);//constructor int getYear( ) const ; int getMonth( ) const ; int getDay( ) const ; private : int year ; int month ; int day ; } ;
119. Inheritance Inheritance: A mechanism used with a hierarchy of classes in which each descendant class inherits the properties (data and operations) of its ancestor class Base class The class being inherited from Derived class the class that inherits 114 Inheritance is an "is-a" …
122. An overridden function in a derived class has the same signature and return type (i.e. prototype) as the function it overrides in its base class.115
123. Example: Overriding 116 Each class has a method Print Person.Print just prints the name Employee.Print prints the name and job title Manager.Print prints name, job title, and department Person Employee Manager Printis overriden. * Static binding is when the compiler can tell which Print to use * dynamic binding is when the determination cannot be made until run time => use the virtual keyword
124. Object-Oriented Programming Inheritance and polymorphism work together to allow programmer to build useful hierarchies of classes that can be put into a library to be reused in different applications Examples: Employee class can reuse features implemented at Person class Only override functions when needed, like print() A program working for Person class still work for Employee object (through polymorphism) Print out all persons,… 117
125. Miscellaneous: I/O in C++ Header files iostream and fstreamdeclare the istream, ostream,and ifstream, ofstream I/O classes. Both cin and cout are class objects These statements declare myInfile as an instance of class ifstream and invoke member function open. ifstream myInfile ; myInfile.open ( “A:mydata.dat” ) ; 118