SlideShare una empresa de Scribd logo
1 de 118
C/C++ Review 1
1. 기본적자료형
기본적인 자료형 (Data Type) 변수(variable): 자료를 저장하는 기억장소 - 모든 변수는 자료형이 지정되어 있어야 하고, 한번 지정된 자료형은 변할 수 없다. - 변수를 사용하기 전에 변수를 미리 정의해야 한다. 자료형_이름 변수리스트; 자료형_이름:  정수형:   int, short int, long,                      unsigned int, … 실수형:    float, double, … 문자형:    char 부울형:    bool, … 연산자 sizeof      - 자료형의 크기 예  sizeof(int)
변수의 이름에대한규칙 중복된 이름의 변수를 사용할 수 없다. 변수 이름에는 알파벳, 숫자, 언더스코어(_)만 포함할 수 있다. 단, 숫자는 변수 이름의 첫 번째 글자로 사용할 수 없다. 변수 이름의 길이에는 제한이 없다. 변수 이름에 포함하는 알파벳은 대소문자를 구분한다. 키워드는 변수의 이름으로 사용할 수 없다.
변수의 이름을 붙일 경우 변수의 용도에 맞는 이름 예: StudentsNumber 변수내의 단어와 단어는 구분 예: StudentsNumber, student_number 필요 없이 긴 이름은 피함
자료형의 종류 C++에서 제공하는 기본 타입들
정수 타입 (Integers) 정수 타입별로 보관할 수 있는 값의 범위 10 진수, 8 진수, 16 진수의 표현 * 32비트 윈도우즈 시스템을 기준으로 한 값 int decimal = 41;		// 10 진수 int octal = 041;		// 8 진수 int hexadecimal = 0x41;	// 16 진수
실수 타입(Floating points) 실수 타입별로 보관할 수 있는 값의 범위 * 32비트 윈도우즈 시스템을 기준으로 한 값
문자 타입 (Characters) 문자 타입별로 보관할 수 있는 값의 범위 문자 타입도 결국은 숫자를 보관한다. * 32비트 윈도우즈 시스템을 기준으로 한 값
부울 타입 (Boolean) 부울 타입은 true 혹은 false의 값을 갖는다. bool b1; bool b2; b1 = true; b2 = false; cout << “b1 = “ << b1 << “”; cout << “b2 = “ << b2 << “”;
형 변환 내부적 형 변환 암시적 형변환은 변수에 대한 처리 과정에서 자동적으로 발생하는 형변환이다.  이 때 값이 변할 수 있다. 예: 실수 타입에서 정수 타입으로 형변환 발생 시 소수점 이하 부분이 잘린다. (반올림 아님) 강제 형 변환  1) (type) expression         예 float f = 66.89;             int i = (int)f;	// i는 66 이 된다.  2) static_cast <자료형 이름>(수식) 예: int n = static_cast<int>(y+0.5);
상수 Define - 매크로 예) #define pi 3.14 const 자료형이름 상수이름 = 초기값;  예) const double pi = 3.14;
연산자 산술연산자   => 산술식 +. -, *, /, %, ++, -- 관계연산자   => 관계식 >, >=, <, <=, ==, != 논리연산자   => 논리식 &&, ||, ! 비트연산자 & (비트 논리곱), | (비트 논리합), ^ (배타적 논리합),  >> (우측 쉬프트), << (좌측 쉬프트) 대입연산자    =     지정문(대입문: assignment statement)에서 대입연산자를 사용 변수 = 식; 예)  x = x + 5;
논리 연산자 (Logical Operators) 논리 연산을 수행한다. bool b1 = true; bool b2 = false; bool and  = b1 && b2; bool or	   = b1 || b2; bool not   = ! b1; * NOT 연산자는 피연산자를 하나만 받는다.
관계연산자와 논리연산자 일반적으로 논리연산자는 관계연산자와 함께 사용한다. 관계연산자의 우선순위가 높으므로 먼저 수행된다. int age = 20;	// 나이 bool male = true;	// 성별 // 20세 이상이면서 남성인지 여부를 알아봄 bool ok = age >= 20 && male == true
연산자의 축약형 연산자의 축약형을 사용해서 번거로운 코딩을 줄일 수 있다.
연산중에 발생하는 형변환 두 피연산자의 타입이 다르다면, 두 피연산자 중에서 보다 큰 타입 쪽으로 형변환이 발생한다. int 보다 작은 타입들은 int 혹은 unsigned int 타입으로 변환된다.
입출력 문 (input/output statement) 입력문     cin >> 변수1 >> 변수2 >> … >>변수n 화면으로부터 자료를 입력 출력문     cout<< 변수(식 혹은 문자열)<< 변수(식 혹은 문자열)… << 변수(식 혹은 문자열) 화면에 출력
2. 제어구조(control structure)
제어구조 판단 구조 if if /else 반복 구조 for While do while
if 문 문법  if (조건) 문장 조건: 1. 관계식 식1 관계연산자 식2 관계 연산자:>,  >= , <, <=, ==, != 2. 논리식 식1 && 식2, 식1 and 식2 식1 || 식2, 식1 or 식2  ! 식,  not 식 블록 여러 개의 문장들을 하나의 단위로 간주 { } 안에 둔다. 조건 문장
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;
시작 x, y,z x<y xy y<z yz x<y xy 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; }
if/else 문 문법 if (조건) 문장1        else  문장2 문제: 세수를 입력하여 최대값을 출력하는 프로그램을 작성하시오 조건 참 거짓 문장1 문장2
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
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; }
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;
참 조건 문장 거짓 sum =0; i = 1; 참 i <= n sum = sum + i i = i + 1; 거짓 while 문 문법 while (조건) 문장 ,[object Object],sum =0; i = 1; while (i <= n) {     sum = sum + i;     i++; }
do/while 문 문법 do  문장       while (조건) 문장 참 조건 거짓
for 문 for(문장1; 조건; 문장2) 문장3; 문장1 –반복시작 전 초기화 조건 –반복 조건 문장3 - 반복 몸체 문장4 –조건과 관련된 문장으로, 몸체(문장3)를 수행한 후, 마지막에 수행  횟수만큼 반복할 때 주로 사용 예 for(i=1; i <=N; i++) 문장 문장1 참 조건 문장3 거짓 문장2
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를 출력 끝
루프 안에서의 break 루프(while, for)나 switch 블록 안에서 break 를 사용하면 블록 밖으로 실행의 흐름이 이동된다.
반복문 안에서의 continue continue는 루프의 나머지 부분을 무시하고 조건을 반복문의 조건을 점검하는 곳으로 점프하여 루프의 다음을 실행하도록 하는 명령어 예:     void main()     {         int i;         for (i=1;i<=50;i++) {         	if (i % 9 == 0)       		continue; 		if (i % 3 == 0) 			printf("%d",i); 	   } }
연속된 입력값의 처리 –표식을 이용 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; }
연속된 입력값의 처리–자료개수를 이용 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; }
3. 배열 (Array)
배열 의미 배열은 연속적인 항목들이 동일한 크기로 메모리에 저장되는 구조로 그 사용이 간편 배열은 동일한 자료 유형이 여러 개 필요한 경우에 이용할 수 있는 자료 구조 크기 배열의 선언은 다음과 같은 구문을 이용 주요 요소는 배열 변수명(이름), 자료형, 그리고 배열의 크기 배열이름 score 로 정수 int 형의 저장 공간이 메모리에 연속적으로 할당된다.
배열 선언 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
배열의원소(Elements of An Array) 배열의특정한 원소(혹은 위치)를 참조하려면 다음을 명시하여야 함 Name of the array (배열 이름) Index of the element (원소 인덱스) :        0 이상 값의 정수 혹은 정수 수식 첫 번째 원소의 인덱스는 0 Example C[0] += 2; C[a + b] = 3; 39
Example 40 An array c has 12 elements ( c[0], c[1], … c[11] ); the value of c[0] is –45.
배열 초기화 – 초기화 리스트 이용 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
배열 초기화 – 루프 이용 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
배열 이용 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
배열 이용 – 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
45 4. 구조체
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 구조체 정의 구조체의 사용 구조체를 사용하기 위해서는 먼저 구조체의 자료 구조를 정의한다. 그 다음에 정의된 구조체의 자료형을 갖는 변수를 선언한다. 구조체 정의 struct student {			 int id;			… 학번 	 char name[10];		… 이름 int dept;		… 학과코드 } ; student	 	 구조체이름, 태그 이름 id, name, dept   	 구조체 원소, 필드(field), 멤버(member) 빠뜨리지 않도록 주의
48 구조체 변수 선언 구조체 정의 후 변수 선언 struct student person; 	struct student p1, p2; 구조체 정의와 함께 변수 선언 struct student {			 	 int id;			 	 char name[10];	 	 int dept;      }  p1, p2;
49 구조체 정의와 변수 선언과의 관계 구조체 정의          구조체 변수 선언 id p1 struct student name id dept name p2 dept id name 자료구조 정의 dept 기억장소 할당
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 예제 (계속)  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 중첩된 구조체 중첩된 구조체 구조체의 멤버로서 다른 구조체를 사용할 수 있음 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;	… 구조체 멤버 접근 방법을 …				     반복하여 적용
53 예제: 복소수 곱셈 복소수의 곱셈 (a+bi) (c+di) = (ac-bd) + (ad+bc)i #include <iostream> struct complex {	/* 복소수 */ double real; 	double imag; }; main() { struct complex x = { 1.0, 2.0 };	/* 곱셈할 복소수 초기화 */ struct complex y = { 2.0, -3.0 }; struct complex m;			/* 곱셈 결과 */ m.real = x.real * y.real - x.imag * y.imag; m.imag = x.real * y.imag + x.imag * y.real; cout << "복소수 곱셈결과 = “ <<m.real < “ + ”<<m.imag << “i”; }
54 구조체의 치환과 비교 구조체의 치환은 허용됨 구조체의 모든 멤버들이 복사됨 구조체의 비교는 허용되지 않음 개별적으로 멤버 비교해야 함 	struct point p1 = {4.0, 10.0}; 	struct point p2; 	p2 = p1;				/* 구조체 치환 */ cout << "p2: x = “ << p2.x << “p2:y = “ << p2.y); 	if (p1.x == p2.x && p1.y == p2.y)	/* 구조체 비교: 멤버 별로  */ cout <<"두 점 p1과 p2는 같다.";
55 구조체 배열 구조체의 배열 여러 개의 같은 구조체 자료형의 모임을 나타내는 자료형 예: 10명의 학생의 자료를 입력 받아서 역순으로 출력 struct student { int id;  string name;  int dept; }; main() { inti; student s[10];		/* s는 구조체의 배열 */ 	for (i=0; i<10; i++) cin >> s[i].id >> s[i].name >> s[i].dept; 	for (i=0; i<10; i++) cout << s[i].id << “ “ << s[i].name << “ “ << s[i].dept << endl; }
5. 함수 (function)
프로그래밍에서의 함수 왜 함수를 사용하는가? 프로그래밍 설계 전략 Divide-and-Conquer 어떤 문제를 해결하기 위해 여러 개의 작은 문제로 쪼개는 것. 사람이 일을 처리하는 방법도 비슷 프로그램의 작성이 용이 반복적인 일을 수행하는 경우 원시파일의 크기를 줄일 수 있음.
함수 유형 라이브러리 함수 라이브러리 함수는 이미 정의되어 있고 컴파일되어 있음 표준 라이브러리 헤더 파일에서 원형을 제공 함수의 원형(prototype)에 맞게 호출 사용자 정의 함수 사용자가 직접 함수 작성 main도 사용자 정의 함수
함수 정의 ,[object Object]
함수정의−함수가 수행할 일을 기술한 C 코드
함수정의의 일반적인 형식{  		declarations 		statements       } 인자(parameter) 리스트 ,[object Object]
 이 함수를 호출할 때에는 이 리스트에 맞게     호출해야함 ,[object Object],반환형(return type) ,[object Object]
 이것이 void이면 반환하는 값이 없다는   것을 나타냄
함수 정의 - 예 예: int max (int x, int y) {     if (x >y)         return x;     else         return y; } 예: double abs(double x) {     if (x >= 0)         return x;     else         return –x; }
return 문장  ,[object Object],(1)     형식     return 식; 의미 - 함수 결과로서 식의 값을 반환하고                 함수를  빠져나간다.     (2) 형식    return; 함수의 반환형이 void 의미 - 이 문장을 수행하면 함수를 빠져나간다. ,[object Object],[object Object]
함수에 자료를 전달하는 방법
실제인자 (actual parameter)      - 함수 사용에 있는 인자 ,[object Object],     - 함수 정의에 있는 인자
함수작성 예 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
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
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
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
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
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
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
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.
//  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
6. 포인터 (pointer)
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
Assign Value to Pointer 74 int alpha; int* intPointer; intPointer = &alpha; If alpha is at address 33,  memory looks like this alpha
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
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
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
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
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;
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
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;
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
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
Pointers: example (cont’d) 84 This memory space cannot be deallocated, as we don’t have a pointer …
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
7. Data Design
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
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
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
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)
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
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
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];
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
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?
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
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
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
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?
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
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
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
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
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
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
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
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
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
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
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
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
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 ; } ;
Object-Oriented Programming Three ingredients in any object-oriented language encapsulation inheritance polymorphism 113

Más contenido relacionado

La actualidad más candente

파이썬 확률과 통계 기초 이해하기
파이썬 확률과 통계 기초 이해하기파이썬 확률과 통계 기초 이해하기
파이썬 확률과 통계 기초 이해하기Yong Joon Moon
 
파이썬+정규표현식+이해하기 20160301
파이썬+정규표현식+이해하기 20160301파이썬+정규표현식+이해하기 20160301
파이썬+정규표현식+이해하기 20160301Yong Joon Moon
 
이펙티브 C++ (7~9)
이펙티브 C++ (7~9)이펙티브 C++ (7~9)
이펙티브 C++ (7~9)익성 조
 
[Swift] Type inference
[Swift] Type inference[Swift] Type inference
[Swift] Type inferenceBill Kim
 
Processing 기초 이해하기_20160713
Processing 기초 이해하기_20160713Processing 기초 이해하기_20160713
Processing 기초 이해하기_20160713Yong Joon Moon
 
C수업자료
C수업자료C수업자료
C수업자료koominsu
 
[Effective Modern C++] Chapter1 - item2
[Effective Modern C++] Chapter1 - item2[Effective Modern C++] Chapter1 - item2
[Effective Modern C++] Chapter1 - item2지환 김
 
[Effective Modern C++] Chapter1 - item1
[Effective Modern C++] Chapter1 - item1[Effective Modern C++] Chapter1 - item1
[Effective Modern C++] Chapter1 - item1지환 김
 
이펙티브 C++ 스터디
이펙티브 C++ 스터디이펙티브 C++ 스터디
이펙티브 C++ 스터디quxn6
 
코딩인카페 C&JAVA 기초과정 C프로그래밍(3)
코딩인카페 C&JAVA 기초과정 C프로그래밍(3)코딩인카페 C&JAVA 기초과정 C프로그래밍(3)
코딩인카페 C&JAVA 기초과정 C프로그래밍(3)유익아카데미
 
Python_numpy_pandas_matplotlib 이해하기_20160815
Python_numpy_pandas_matplotlib 이해하기_20160815Python_numpy_pandas_matplotlib 이해하기_20160815
Python_numpy_pandas_matplotlib 이해하기_20160815Yong Joon Moon
 
Python array.array 모듈 이해하기
Python array.array 모듈 이해하기Python array.array 모듈 이해하기
Python array.array 모듈 이해하기Yong Joon Moon
 
파이썬 문자열 이해하기
파이썬 문자열 이해하기파이썬 문자열 이해하기
파이썬 문자열 이해하기Yong Joon Moon
 
Matplotlib 기초 이해하기_20160730
Matplotlib 기초 이해하기_20160730Matplotlib 기초 이해하기_20160730
Matplotlib 기초 이해하기_20160730Yong Joon Moon
 
파이썬 문자열 이해하기
파이썬 문자열 이해하기파이썬 문자열 이해하기
파이썬 문자열 이해하기Yong Joon Moon
 
파이썬 숫자,변수,문자열
파이썬 숫자,변수,문자열파이썬 숫자,변수,문자열
파이썬 숫자,변수,문자열HoYong Na
 

La actualidad más candente (20)

파이썬 확률과 통계 기초 이해하기
파이썬 확률과 통계 기초 이해하기파이썬 확률과 통계 기초 이해하기
파이썬 확률과 통계 기초 이해하기
 
파이썬+정규표현식+이해하기 20160301
파이썬+정규표현식+이해하기 20160301파이썬+정규표현식+이해하기 20160301
파이썬+정규표현식+이해하기 20160301
 
이펙티브 C++ (7~9)
이펙티브 C++ (7~9)이펙티브 C++ (7~9)
이펙티브 C++ (7~9)
 
[Swift] Type inference
[Swift] Type inference[Swift] Type inference
[Swift] Type inference
 
C++11
C++11C++11
C++11
 
Processing 기초 이해하기_20160713
Processing 기초 이해하기_20160713Processing 기초 이해하기_20160713
Processing 기초 이해하기_20160713
 
C수업자료
C수업자료C수업자료
C수업자료
 
[Effective Modern C++] Chapter1 - item2
[Effective Modern C++] Chapter1 - item2[Effective Modern C++] Chapter1 - item2
[Effective Modern C++] Chapter1 - item2
 
[Effective Modern C++] Chapter1 - item1
[Effective Modern C++] Chapter1 - item1[Effective Modern C++] Chapter1 - item1
[Effective Modern C++] Chapter1 - item1
 
이펙티브 C++ 스터디
이펙티브 C++ 스터디이펙티브 C++ 스터디
이펙티브 C++ 스터디
 
Modern effective cpp 항목1
Modern effective cpp 항목1Modern effective cpp 항목1
Modern effective cpp 항목1
 
코딩인카페 C&JAVA 기초과정 C프로그래밍(3)
코딩인카페 C&JAVA 기초과정 C프로그래밍(3)코딩인카페 C&JAVA 기초과정 C프로그래밍(3)
코딩인카페 C&JAVA 기초과정 C프로그래밍(3)
 
Python_numpy_pandas_matplotlib 이해하기_20160815
Python_numpy_pandas_matplotlib 이해하기_20160815Python_numpy_pandas_matplotlib 이해하기_20160815
Python_numpy_pandas_matplotlib 이해하기_20160815
 
Python array.array 모듈 이해하기
Python array.array 모듈 이해하기Python array.array 모듈 이해하기
Python array.array 모듈 이해하기
 
파이썬 문자열 이해하기
파이썬 문자열 이해하기파이썬 문자열 이해하기
파이썬 문자열 이해하기
 
Java standard(8~13)
Java standard(8~13)Java standard(8~13)
Java standard(8~13)
 
Matplotlib 기초 이해하기_20160730
Matplotlib 기초 이해하기_20160730Matplotlib 기초 이해하기_20160730
Matplotlib 기초 이해하기_20160730
 
파이썬 문자열 이해하기
파이썬 문자열 이해하기파이썬 문자열 이해하기
파이썬 문자열 이해하기
 
9. pointer
9. pointer9. pointer
9. pointer
 
파이썬 숫자,변수,문자열
파이썬 숫자,변수,문자열파이썬 숫자,변수,문자열
파이썬 숫자,변수,문자열
 

Destacado

잡코리아 글로벌 프런티어 5기_Good Bye My Car~!_탐방 보고서
잡코리아 글로벌 프런티어 5기_Good Bye My Car~!_탐방 보고서잡코리아 글로벌 프런티어 5기_Good Bye My Car~!_탐방 보고서
잡코리아 글로벌 프런티어 5기_Good Bye My Car~!_탐방 보고서잡코리아 글로벌 프런티어
 
임지연 포트폴리오
임지연 포트폴리오임지연 포트폴리오
임지연 포트폴리오Jiyeon Lim
 
텀블러
텀블러텀블러
텀블러Trerson
 
모션그래픽 중간발표
모션그래픽 중간발표모션그래픽 중간발표
모션그래픽 중간발표Da Hye Kim
 
XE 레이아웃 실습 강의자료
XE 레이아웃 실습 강의자료XE 레이아웃 실습 강의자료
XE 레이아웃 실습 강의자료Jowrney Kim
 
예술로서의디자인 2
예술로서의디자인 2예술로서의디자인 2
예술로서의디자인 2hyein1227
 
D.M Project_1
D.M Project_1D.M Project_1
D.M Project_1수 지
 
[2015년 11월] TV 인터넷관심도 월간 리포트
[2015년 11월] TV 인터넷관심도 월간 리포트[2015년 11월] TV 인터넷관심도 월간 리포트
[2015년 11월] TV 인터넷관심도 월간 리포트ZUM internet
 
SnDTech Company Profile (201506)
SnDTech Company Profile (201506)SnDTech Company Profile (201506)
SnDTech Company Profile (201506)sndtech
 
대준아미대가자2
대준아미대가자2대준아미대가자2
대준아미대가자2다솜 김
 
색채연구보고서 최혜진
색채연구보고서 최혜진색채연구보고서 최혜진
색채연구보고서 최혜진Jinny525
 
모션그래픽 중간발표2
모션그래픽 중간발표2모션그래픽 중간발표2
모션그래픽 중간발표2Da Hye Kim
 
Bada중간 발표
Bada중간 발표Bada중간 발표
Bada중간 발표태훈 정
 
Web conference
Web conferenceWeb conference
Web conferenceJongHo Lee
 
대준이 와이어프레임부터디자인
대준이 와이어프레임부터디자인대준이 와이어프레임부터디자인
대준이 와이어프레임부터디자인지은 이
 
졸전리서치 선행공유앱
졸전리서치 선행공유앱졸전리서치 선행공유앱
졸전리서치 선행공유앱Jungsook Baek
 
1414003 이혜인 개인과제
1414003 이혜인 개인과제1414003 이혜인 개인과제
1414003 이혜인 개인과제hyein1227
 

Destacado (20)

강의자료8
강의자료8강의자료8
강의자료8
 
잡코리아 글로벌 프런티어 5기_Good Bye My Car~!_탐방 보고서
잡코리아 글로벌 프런티어 5기_Good Bye My Car~!_탐방 보고서잡코리아 글로벌 프런티어 5기_Good Bye My Car~!_탐방 보고서
잡코리아 글로벌 프런티어 5기_Good Bye My Car~!_탐방 보고서
 
임지연 포트폴리오
임지연 포트폴리오임지연 포트폴리오
임지연 포트폴리오
 
텀블러
텀블러텀블러
텀블러
 
모션그래픽 중간발표
모션그래픽 중간발표모션그래픽 중간발표
모션그래픽 중간발표
 
XE 레이아웃 실습 강의자료
XE 레이아웃 실습 강의자료XE 레이아웃 실습 강의자료
XE 레이아웃 실습 강의자료
 
예술로서의디자인 2
예술로서의디자인 2예술로서의디자인 2
예술로서의디자인 2
 
D.M Project_1
D.M Project_1D.M Project_1
D.M Project_1
 
기획서
기획서기획서
기획서
 
[2015년 11월] TV 인터넷관심도 월간 리포트
[2015년 11월] TV 인터넷관심도 월간 리포트[2015년 11월] TV 인터넷관심도 월간 리포트
[2015년 11월] TV 인터넷관심도 월간 리포트
 
SnDTech Company Profile (201506)
SnDTech Company Profile (201506)SnDTech Company Profile (201506)
SnDTech Company Profile (201506)
 
대준아미대가자2
대준아미대가자2대준아미대가자2
대준아미대가자2
 
색채연구보고서 최혜진
색채연구보고서 최혜진색채연구보고서 최혜진
색채연구보고서 최혜진
 
모션그래픽 중간발표2
모션그래픽 중간발표2모션그래픽 중간발표2
모션그래픽 중간발표2
 
시각장애인을 위한 시각디자인 - 강부경
시각장애인을 위한 시각디자인 - 강부경시각장애인을 위한 시각디자인 - 강부경
시각장애인을 위한 시각디자인 - 강부경
 
Bada중간 발표
Bada중간 발표Bada중간 발표
Bada중간 발표
 
Web conference
Web conferenceWeb conference
Web conference
 
대준이 와이어프레임부터디자인
대준이 와이어프레임부터디자인대준이 와이어프레임부터디자인
대준이 와이어프레임부터디자인
 
졸전리서치 선행공유앱
졸전리서치 선행공유앱졸전리서치 선행공유앱
졸전리서치 선행공유앱
 
1414003 이혜인 개인과제
1414003 이혜인 개인과제1414003 이혜인 개인과제
1414003 이혜인 개인과제
 

Similar a C review

C수업자료
C수업자료C수업자료
C수업자료koominsu
 
배열과 포인터
배열과 포인터배열과 포인터
배열과 포인터영기 김
 
2015 Kitel C 언어 강좌3
2015 Kitel C 언어 강좌32015 Kitel C 언어 강좌3
2015 Kitel C 언어 강좌3ssuseraf62e91
 
변수 이름의 효과
변수 이름의 효과변수 이름의 효과
변수 이름의 효과민욱 이
 
2013 C++ Study For Students #1
2013 C++ Study For Students #12013 C++ Study For Students #1
2013 C++ Study For Students #1Chris Ohk
 
문과생 대상 파이썬을 활용한 데이터 분석 강의
문과생 대상 파이썬을 활용한 데이터 분석 강의문과생 대상 파이썬을 활용한 데이터 분석 강의
문과생 대상 파이썬을 활용한 데이터 분석 강의Kwangyoun Jung
 
게임프로그래밍입문 3주차
게임프로그래밍입문 3주차게임프로그래밍입문 3주차
게임프로그래밍입문 3주차Yeonah Ki
 
불어오는 변화의 바람, From c++98 to c++11, 14
불어오는 변화의 바람, From c++98 to c++11, 14 불어오는 변화의 바람, From c++98 to c++11, 14
불어오는 변화의 바람, From c++98 to c++11, 14 명신 김
 
공유 Jdk 7-2-project coin
공유 Jdk 7-2-project coin공유 Jdk 7-2-project coin
공유 Jdk 7-2-project coinknight1128
 
14장 - 15장 예외처리, 템플릿
14장 - 15장 예외처리, 템플릿14장 - 15장 예외처리, 템플릿
14장 - 15장 예외처리, 템플릿유석 남
 
C++ 11 에 대해서 쉽게 알아봅시다 1부
C++ 11 에 대해서 쉽게 알아봅시다 1부C++ 11 에 대해서 쉽게 알아봅시다 1부
C++ 11 에 대해서 쉽게 알아봅시다 1부Gwangwhi Mah
 
포트폴리오에서 사용한 모던 C++
포트폴리오에서 사용한 모던 C++포트폴리오에서 사용한 모던 C++
포트폴리오에서 사용한 모던 C++KWANGIL KIM
 
파이썬정리 20160130
파이썬정리 20160130파이썬정리 20160130
파이썬정리 20160130Yong Joon Moon
 
Boost라이브러리의내부구조 20151111 서진택
Boost라이브러리의내부구조 20151111 서진택Boost라이브러리의내부구조 20151111 서진택
Boost라이브러리의내부구조 20151111 서진택JinTaek Seo
 
[2011 05 21] 4장 제어
[2011 05 21] 4장 제어[2011 05 21] 4장 제어
[2011 05 21] 4장 제어Jong Pil Won
 
[2011 05 21] 4장 제어
[2011 05 21] 4장 제어[2011 05 21] 4장 제어
[2011 05 21] 4장 제어Jong Pil Won
 

Similar a C review (20)

C수업자료
C수업자료C수업자료
C수업자료
 
배열과 포인터
배열과 포인터배열과 포인터
배열과 포인터
 
2015 Kitel C 언어 강좌3
2015 Kitel C 언어 강좌32015 Kitel C 언어 강좌3
2015 Kitel C 언어 강좌3
 
06장 함수
06장 함수06장 함수
06장 함수
 
변수 이름의 효과
변수 이름의 효과변수 이름의 효과
변수 이름의 효과
 
2013 C++ Study For Students #1
2013 C++ Study For Students #12013 C++ Study For Students #1
2013 C++ Study For Students #1
 
강의자료3
강의자료3강의자료3
강의자료3
 
문과생 대상 파이썬을 활용한 데이터 분석 강의
문과생 대상 파이썬을 활용한 데이터 분석 강의문과생 대상 파이썬을 활용한 데이터 분석 강의
문과생 대상 파이썬을 활용한 데이터 분석 강의
 
게임프로그래밍입문 3주차
게임프로그래밍입문 3주차게임프로그래밍입문 3주차
게임프로그래밍입문 3주차
 
불어오는 변화의 바람, From c++98 to c++11, 14
불어오는 변화의 바람, From c++98 to c++11, 14 불어오는 변화의 바람, From c++98 to c++11, 14
불어오는 변화의 바람, From c++98 to c++11, 14
 
강의자료4
강의자료4강의자료4
강의자료4
 
java_2장.pptx
java_2장.pptxjava_2장.pptx
java_2장.pptx
 
공유 Jdk 7-2-project coin
공유 Jdk 7-2-project coin공유 Jdk 7-2-project coin
공유 Jdk 7-2-project coin
 
14장 - 15장 예외처리, 템플릿
14장 - 15장 예외처리, 템플릿14장 - 15장 예외처리, 템플릿
14장 - 15장 예외처리, 템플릿
 
C++ 11 에 대해서 쉽게 알아봅시다 1부
C++ 11 에 대해서 쉽게 알아봅시다 1부C++ 11 에 대해서 쉽게 알아봅시다 1부
C++ 11 에 대해서 쉽게 알아봅시다 1부
 
포트폴리오에서 사용한 모던 C++
포트폴리오에서 사용한 모던 C++포트폴리오에서 사용한 모던 C++
포트폴리오에서 사용한 모던 C++
 
파이썬정리 20160130
파이썬정리 20160130파이썬정리 20160130
파이썬정리 20160130
 
Boost라이브러리의내부구조 20151111 서진택
Boost라이브러리의내부구조 20151111 서진택Boost라이브러리의내부구조 20151111 서진택
Boost라이브러리의내부구조 20151111 서진택
 
[2011 05 21] 4장 제어
[2011 05 21] 4장 제어[2011 05 21] 4장 제어
[2011 05 21] 4장 제어
 
[2011 05 21] 4장 제어
[2011 05 21] 4장 제어[2011 05 21] 4장 제어
[2011 05 21] 4장 제어
 

Más de Young Wook Kim

Más de Young Wook Kim (6)

강의자료10
강의자료10강의자료10
강의자료10
 
강의자료9
강의자료9강의자료9
강의자료9
 
강의자료7
강의자료7강의자료7
강의자료7
 
강의자료6
강의자료6강의자료6
강의자료6
 
강의자료 2
강의자료 2강의자료 2
강의자료 2
 
강의자료5
강의자료5강의자료5
강의자료5
 

C review

  • 3. 기본적인 자료형 (Data Type) 변수(variable): 자료를 저장하는 기억장소 - 모든 변수는 자료형이 지정되어 있어야 하고, 한번 지정된 자료형은 변할 수 없다. - 변수를 사용하기 전에 변수를 미리 정의해야 한다. 자료형_이름 변수리스트; 자료형_이름: 정수형: int, short int, long, unsigned int, … 실수형: float, double, … 문자형: char 부울형: bool, … 연산자 sizeof - 자료형의 크기 예 sizeof(int)
  • 4. 변수의 이름에대한규칙 중복된 이름의 변수를 사용할 수 없다. 변수 이름에는 알파벳, 숫자, 언더스코어(_)만 포함할 수 있다. 단, 숫자는 변수 이름의 첫 번째 글자로 사용할 수 없다. 변수 이름의 길이에는 제한이 없다. 변수 이름에 포함하는 알파벳은 대소문자를 구분한다. 키워드는 변수의 이름으로 사용할 수 없다.
  • 5. 변수의 이름을 붙일 경우 변수의 용도에 맞는 이름 예: StudentsNumber 변수내의 단어와 단어는 구분 예: StudentsNumber, student_number 필요 없이 긴 이름은 피함
  • 6. 자료형의 종류 C++에서 제공하는 기본 타입들
  • 7. 정수 타입 (Integers) 정수 타입별로 보관할 수 있는 값의 범위 10 진수, 8 진수, 16 진수의 표현 * 32비트 윈도우즈 시스템을 기준으로 한 값 int decimal = 41; // 10 진수 int octal = 041; // 8 진수 int hexadecimal = 0x41; // 16 진수
  • 8. 실수 타입(Floating points) 실수 타입별로 보관할 수 있는 값의 범위 * 32비트 윈도우즈 시스템을 기준으로 한 값
  • 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;
  • 13. 연산자 산술연산자 => 산술식 +. -, *, /, %, ++, -- 관계연산자 => 관계식 >, >=, <, <=, ==, != 논리연산자 => 논리식 &&, ||, ! 비트연산자 & (비트 논리곱), | (비트 논리합), ^ (배타적 논리합), >> (우측 쉬프트), << (좌측 쉬프트) 대입연산자 = 지정문(대입문: assignment statement)에서 대입연산자를 사용 변수 = 식; 예) x = x + 5;
  • 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
  • 16. 연산자의 축약형 연산자의 축약형을 사용해서 번거로운 코딩을 줄일 수 있다.
  • 17. 연산중에 발생하는 형변환 두 피연산자의 타입이 다르다면, 두 피연산자 중에서 보다 큰 타입 쪽으로 형변환이 발생한다. int 보다 작은 타입들은 int 혹은 unsigned int 타입으로 변환된다.
  • 18. 입출력 문 (input/output statement) 입력문 cin >> 변수1 >> 변수2 >> … >>변수n 화면으로부터 자료를 입력 출력문 cout<< 변수(식 혹은 문자열)<< 변수(식 혹은 문자열)… << 변수(식 혹은 문자열) 화면에 출력
  • 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 xy y<z yz x<y xy 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;
  • 28.
  • 29. do/while 문 문법 do 문장 while (조건) 문장 참 조건 거짓
  • 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; … 구조체 멤버 접근 방법을 … 반복하여 적용
  • 53. 53 예제: 복소수 곱셈 복소수의 곱셈 (a+bi) (c+di) = (ac-bd) + (ad+bc)i #include <iostream> struct complex { /* 복소수 */ double real; double imag; }; main() { struct complex x = { 1.0, 2.0 }; /* 곱셈할 복소수 초기화 */ struct complex y = { 2.0, -3.0 }; struct complex m; /* 곱셈 결과 */ m.real = x.real * y.real - x.imag * y.imag; m.imag = x.real * y.imag + x.imag * y.real; cout << "복소수 곱셈결과 = “ <<m.real < “ + ”<<m.imag << “i”; }
  • 54. 54 구조체의 치환과 비교 구조체의 치환은 허용됨 구조체의 모든 멤버들이 복사됨 구조체의 비교는 허용되지 않음 개별적으로 멤버 비교해야 함 struct point p1 = {4.0, 10.0}; struct point p2; p2 = p1; /* 구조체 치환 */ cout << "p2: x = “ << p2.x << “p2:y = “ << p2.y); if (p1.x == p2.x && p1.y == p2.y) /* 구조체 비교: 멤버 별로 */ cout <<"두 점 p1과 p2는 같다.";
  • 55. 55 구조체 배열 구조체의 배열 여러 개의 같은 구조체 자료형의 모임을 나타내는 자료형 예: 10명의 학생의 자료를 입력 받아서 역순으로 출력 struct student { int id; string name; int dept; }; main() { inti; student s[10]; /* s는 구조체의 배열 */ for (i=0; i<10; i++) cin >> s[i].id >> s[i].name >> s[i].dept; for (i=0; i<10; i++) cout << s[i].id << “ “ << s[i].name << “ “ << s[i].dept << endl; }
  • 57. 프로그래밍에서의 함수 왜 함수를 사용하는가? 프로그래밍 설계 전략 Divide-and-Conquer 어떤 문제를 해결하기 위해 여러 개의 작은 문제로 쪼개는 것. 사람이 일을 처리하는 방법도 비슷 프로그램의 작성이 용이 반복적인 일을 수행하는 경우 원시파일의 크기를 줄일 수 있음.
  • 58. 함수 유형 라이브러리 함수 라이브러리 함수는 이미 정의되어 있고 컴파일되어 있음 표준 라이브러리 헤더 파일에서 원형을 제공 함수의 원형(prototype)에 맞게 호출 사용자 정의 함수 사용자가 직접 함수 작성 main도 사용자 정의 함수
  • 59.
  • 61.
  • 62.
  • 63. 이것이 void이면 반환하는 값이 없다는 것을 나타냄
  • 64. 함수 정의 - 예 예: int max (int x, int y) { if (x >y) return x; else return y; } 예: double abs(double x) { if (x >= 0) return x; else return –x; }
  • 65.
  • 67.
  • 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 = &alpha; 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
  • 89. Pointers: example (cont’d) 84 This memory space cannot be deallocated, as we don’t have a pointer …
  • 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 ; } ;
  • 118. Object-Oriented Programming Three ingredients in any object-oriented language encapsulation inheritance polymorphism 113
  • 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" …
  • 120.
  • 121. Derived classes override function as appropriate.
  • 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