C/C++ Review1
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 << “\n”;cout << “b2 = “ << b2 << “\n”;
형 변환내부적 형 변환암시적 형변환은 변수에 대한 처리 과정에서 자동적으로 발생하는 형변환이다. 이 때 값이 변할 수 있다. 예: 실수 타입에서 정수 타입으로 형변환 발생 시 소수점 이하 부분이 잘린다. (반올림 아님)강제 형 변환 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.14const 자료형이름 상수이름 = 초기값; 예) 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)
제어구조판단 구조ifif /else반복 구조forWhiledo 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 > ca != 0 && b*b > 4*a*c!more    // bool more;
시작x, y,zx<yxyy<zyzx<yxyx,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\n";	break;case 8:	cout << " 학점: B\n";	break;case 7:	cout << " 학점: C\n";	break;case 6:	cout << " 학점: D\n";	break;default:	cout << " 학점: D\n";	break;}
exp1 ? exp2 : exp3int 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 <= nsum = sum + ii = i + 1;거짓while 문문법while (조건)문장문제: 1부터 n까지의 합을 구하는 프로그램을 작성하시오.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 <= Nproduct= product * i거짓i++;product를 출력끝
루프 안에서의 break루프(while, for)나 switch 블록 안에서 break 를 사용하면 블록 밖으로 실행의 흐름이 이동된다.
반복문 안에서의 continuecontinue는 루프의 나머지 부분을 무시하고 조건을 반복문의 조건을 점검하는 곳으로 점프하여 루프의 다음을 실행하도록 하는 명령어예:    void main()    {        int i;        for (i=1;i<=50;i++) {        	if (i % 9 == 0)      		continue;		if (i % 3 == 0)			printf("%d\n",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 ];Exampleint 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 이상 값의 정수 혹은 정수 수식첫 번째 원소의 인덱스는 0ExampleC[0] += 2;C[a + b] = 3;39
Example40An 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.Examplesint 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 elementsDeclare array, specify number of elementsUse repetition statement to loop for each elementExample: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 checkingReferring 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 1Example: 배열 원소들의 합  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
454. 구조체
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구조체 정의와 변수 선언과의 관계구조체 정의          구조체 변수 선언idp1struct studentnameiddeptnamep2deptidname자료구조 정의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는 같다.\n";
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도 사용자 정의 함수
함수 정의프로그램은 하나 이상의 함수로 구성됨
함수정의−함수가 수행할 일을 기술한 C 코드
함수정의의 일반적인 형식{ 		declarations		statements      }인자(parameter) 리스트 이 함수가 가지는 인자의 목록
 이 함수를 호출할 때에는 이 리스트에 맞게     호출해야함 이것이 void이면 인자를 갖지 않음을 나타냄반환형(return type)함수가 반환하는 값의 자료형
 이것이 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 문장 return 문(1)     형식     return 식;의미 - 함수 결과로서 식의 값을 반환하고                함수를  빠져나간다.    (2) 형식    return;함수의 반환형이 void의미 - 이 문장을 수행하면 함수를 빠져나간다.함수의 수행 중 마지막을 만나면 함수를 빠져나간다. – return 문장의 수행과 동일한 효과 함수의 인자(parameter)인자(parameter)
함수에 자료를 전달하는 방법
실제인자 (actual parameter)      - 함수 사용에 있는 인자형식인자 (formal parameter)     - 함수 정의에 있는 인자
함수작성 예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; 63Should print out: x=20 y=10
C/C++ functionvoid 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;}64a,b: formal parameters올바르게 동작하느냐? Call by value:  A copy of the value of myInterger1 and myInterger2  are passed to ExchangeValue.actual parameters
C++ Tips65CALLINGBLOCKFUNCTION  CALLEDPass-by-value sends a copyof the value of the actual  parameterSO, the actual parameter cannot be changed by the function
C++ Tips66CALLINGBLOCKFUNCTION  CALLEDPass-by-reference sends the location(memory address) of the actual parameterthe actual parameter can be changed by the function
Call-by-referenceGood for performance reason:  eliminate copying overheadCalled the same way as call-by-valueint squareByValue (int x);int squareByReference (int & x);int x,z;…squareByValue(x);squareByReference(z);Bad for security: called function can corrupt caller’s dataSolution: use const quantifier67
C/C++ function: call by referencevoid 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;}68a,b: formal parameters제대로동작함!actual parameters
Passing Arrays as ParametersIn 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 functionExample:// 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 );70If 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 VariableA variable whose value is the address of a location in memoryi.e., a variable that points to some address in memory…type * pointer_variable_name;73int* intPointer
Assign Value to Pointer74int alpha;int* intPointer;intPointer = &alpha;If alpha is at address 33, memory looks like thisalpha
Pointer Types75                    2000                       12                     x3000    2000 ptrint  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 points76                    2000                       12                     x3000    2000 ptrint  x; x = 12; int*  ptr; ptr = &x; std::cout  <<  *ptr;*ptr is the value in the place to which ptr points
77Pointer: Dereference Operator (*)                    2000                    12    5                     x3000   2000 ptrint  x; x = 12; int*  ptr; ptr = &x; *ptr = 5;// changes the value 			// at adddress ptr to 5
Pointer Types78char  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                     ch5000                    6000   4000                    4000  q                        p
79intPtrmoneyPointer TypesAll pointer variables should be initialized to be NULLA pointer that points to nothing; available in <cstdlib>NULL is defined to be 0;But NULL is not memory address 0int * intPtr = NULL;Float * money = NULL;
Review: lifetime of variables or objectsGlobal variables/objects: start from before the program starts until main() endsint 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/blockDynamical variables/objects: created using new(), malloc() callsRemains alive until delete() is called to free the memoryDestroyed upon the program exits80
Dynamic allocation (new operator)Allocation of memory space for a variable at run time (as opposed to static allocation at compile time)81int * intPointer;intPointer = new int;
Deallocate allocated memoryDynamically allocated memory needs to be deallocated when it’s no more usedOtherwise, memory leak will degrade performancedelete operator returns memory to system  delete p;Value of p is unchanged, i.e. pointing to a deallocated memoryAccessing 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 important82
Pointers: examplesFigure 4-3(a) Declaring pointer variables; (b) pointing to statically allocated memory; (c) assigning a value;(d) allocating memory dynamically; (e) assigning a value83
Pointers: example (cont’d)84This memory space cannot be deallocated, as we don’t have a pointer …
Dynamically Allocated ArraysUse new operator to allocate an array dynamicallyint arraySize;		//ask user to enter arraySize…		//double *anArray = new double[arraySize];arraySize has a value determined at run timeDynamically allocated array can be increaseddouble *oldArray = anArray; 		 anArray = newdouble[2*arraySize];   		// copy from oldArray to anArray  		delete [] oldArray; // deallocate oldArray85
7. Data Design
Let’s focus on: DataData:  the representation of information in a manner suitable for communication or analysis by humans or machinesData are the nouns of the programming world: The objects that are manipulatedThe information that is processedDifferent view about dataApplication 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 Addresspointer    referenceC++  Built-In Data TypesSimpleComposite IntegralFloatingarray   struct   union   classchar  short   int  long  enumfloat  double   long double
Using C/C++ Data TypeAs a C/C++ programmer, we know Based on the application,  we model them as different “variables”Age: integerGender: enumerationName: array of char, or stringAlso we know what kind of operations each data type supportsWe do not worry about how an integer is implementedUnless in computer organization class …89
C++ programmer are user of int90TYPE intRepresentation of	int   as 16 bits two’s     complement	+Implementation of       OperationsValue range:  INT_MIN . . INT_MAX     Operations:     +  prefix     -  prefix     +  infix     -  infix*  infix     /  infix%  infixRelational Operators         infix(inside)
Different Views of DataApplication (or user) levelmodeling real-life data in a specific contextWhen to use a certain data type ?Logical (or ADT) levelabstract view of the domain and operationsWhatHow to use the data type ?Implementation levelspecific representation of the structure to hold the data items, and the coding for operationsHow to implement the data type ?   91
Different Views of Data: Library ExampleApplication (or user) levelLibrary of Congress, or Baltimore County Public LibraryA 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 bookA library’s necessary functions to outside worldImplementation levelrepresentation of the structure to hold the “books” and the coding for operationsHow a specific library is implemented (how are books organized…)? 92
A two-dimensional arrayA 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]93Logic view of 2D array:all a C++ program needs to knowlogical levelint dataTable[10][6];
Many recurrent data typesListQueue:  First In First OutOperating System: process queues, printing job queueStack: Last in First outCalling stackCompiler: to parse expressionsGraph:Model computer network….94Provide a high-level data type with these logic  property
Data Abstraction: the ideaData Abstraction: the separation of a data type’s logical properties from its implementationUser of the data type only needs to understand its logical property, no need to worry about its implementation95LOGICAL PROPERTIES	IMPLEMENTATIONWhat are the possible values?		How can this be done in C++?What operations will be needed?
Abstract Data Type: A logic viewAbstract Data Type is a specification ofa 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 featureTransformers (mutators): operations that change the state of one or more data values in an ADTObservers: operations that allow us to observe the state of the ADTIterators: operations that allow us to access each member of a data structure sequentiallyAbstract Data Type is implementation independent96
OOP & ADTObject-oriented language provide mechanism for specifying ADT and implementing ADTClassAn unstructured type that encapsulates a fixed number of data components (data members) with the functions (member functions) that manipulate thempredefined operations on an instance of a class are whole assignment and component accessClientSoftware that uses (declares and manipulates) objects (instances) of a particular class to solve some problem97
Object-Oriented Programming: BasicsClass an unstructured type that encapsulates a fixed number of data components (data members) with the functions (called member functions) that manipulate themObjectAn instance of a classMethodA public member function of a classInstance variable (Data Member)A private data member of a class98
Higher-Level AbstractionClass specificationA specification of the class members (data and functions) with their types and/or parametersClass implementationThe code that implements the class functions99Why  would you want toput them in separate files?
Classes vs. StructsWithout using public and private, member functions and data areprivate by default in classes public by default in structs.Usually, there is no member functions defined in structsstruct  is passive dataclass is active data100
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 dayprivate :			     //  3 private data members	int  year ;           	int  month ;          	int	 day ;} ;101101
Use of C++ data type classVariables 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; }103How 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 codeDateType :: 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 operator105
C++ Classes: ConstructorsInvoked/called (automatically) when an object of the class is declared/createdA class can have several constructorsA default constructor has no argumentsdifferent 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 constructors106
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 ;}107107
C++ Classes: Destructors*Called (automatically) when an object’s lifetime endsTo free up resources taken by the object, esp. memoryEach class has one destructorIf you don’t need to free up resources, you can omit define destructor and the compiler will generate a default destructor108
C++ Namespaces*A mechanism for logically grouping declarations and definitions into a common declarative regionnamespace myNamespace  {    // Definitions    // Declarations . . .} //end myNamespaceThe contents of the namespace can be accessed by code inside or outside the namespaceUse the scope resolution operator (::) to access elements from outside the namespaceAlternatively, the using declaration allows the names of the elements to be used directly109
C++ Namespace: simple example*Creating a namespacenamespace smallNamespace{int count = 0;void abc();} // end smallNamespaceUsing a namespacesmallNamesapce::count=0;usingnamespace smallNamespace;count +=1;abc(); 110
C++ std namespace*Items declared in the C++ Standard Library are declared in the std namespaceYou 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
EncapsulationJust as a capsule protects its contents, the class construct  protects its data members112//  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 ProgrammingThree ingredients in any object-oriented languageencapsulationinheritancepolymorphism113

C review

  • 1.
  • 2.
  • 3.
    기본적인 자료형 (DataType)변수(variable): 자료를 저장하는 기억장소- 모든 변수는 자료형이 지정되어 있어야 하고, 한번 지정된 자료형은 변할 수 없다.- 변수를 사용하기 전에 변수를 미리 정의해야 한다.자료형_이름 변수리스트;자료형_이름: 정수형: int, short int, long, unsigned int, …실수형: float, double, …문자형: char부울형: bool, …연산자 sizeof - 자료형의 크기예 sizeof(int)
  • 4.
    변수의 이름에대한규칙중복된 이름의변수를 사용할 수 없다.변수 이름에는 알파벳, 숫자, 언더스코어(_)만 포함할 수 있다.단, 숫자는 변수 이름의 첫 번째 글자로 사용할 수 없다.변수 이름의 길이에는 제한이 없다.변수 이름에 포함하는 알파벳은 대소문자를 구분한다.키워드는 변수의 이름으로 사용할 수 없다.
  • 5.
    변수의 이름을 붙일경우변수의 용도에 맞는 이름예: StudentsNumber변수내의 단어와 단어는 구분예: StudentsNumber, student_number필요 없이 긴 이름은 피함
  • 6.
  • 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 << “\n”;cout << “b2 = “ << b2 << “\n”;
  • 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.14const 자료형이름 상수이름 = 초기값; 예) const double pi = 3.14;
  • 13.
    연산자산술연산자 => 산술식+. -, *, /, %, ++, --관계연산자 => 관계식>, >=, <, <=, ==, !=논리연산자 => 논리식&&, ||, !비트연산자& (비트 논리곱), | (비트 논리합), ^ (배타적 논리합), >> (우측 쉬프트), << (좌측 쉬프트)대입연산자 = 지정문(대입문: assignment statement)에서 대입연산자를 사용변수 = 식;예) x = x + 5;
  • 14.
    논리 연산자 (LogicalOperators)논리 연산을 수행한다.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/outputstatement)입력문 cin >> 변수1 >> 변수2 >> … >>변수n화면으로부터 자료를 입력출력문 cout<< 변수(식 혹은 문자열)<< 변수(식 혹은 문자열)… << 변수(식 혹은 문자열)화면에 출력
  • 19.
  • 20.
  • 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 > ca != 0 && b*b > 4*a*c!more // bool more;
  • 23.
    시작x, y,zx<yxyy<zyzx<yxyx,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\n"; break;case 8: cout << " 학점: B\n"; break;case 7: cout << " 학점: C\n"; break;case 6: cout << " 학점: D\n"; break;default: cout << " 학점: D\n"; break;}
  • 27.
    exp1 ? exp2: exp3int 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.
    참조건문장거짓sum =0;i =1;참i <= nsum = sum + ii = i + 1;거짓while 문문법while (조건)문장문제: 1부터 n까지의 합을 구하는 프로그램을 작성하시오.sum =0;i = 1;while (i <= n){ sum = sum + i; i++;}
  • 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 <= Nproduct= product * i거짓i++;product를 출력끝
  • 32.
    루프 안에서의 break루프(while,for)나 switch 블록 안에서 break 를 사용하면 블록 밖으로 실행의 흐름이 이동된다.
  • 33.
    반복문 안에서의 continuecontinue는루프의 나머지 부분을 무시하고 조건을 반복문의 조건을 점검하는 곳으로 점프하여 루프의 다음을 실행하도록 하는 명령어예: void main() { int i; for (i=1;i<=50;i++) { if (i % 9 == 0) continue; if (i % 3 == 0) printf("%d\n",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;}
  • 36.
  • 37.
    배열의미배열은 연속적인 항목들이동일한 크기로 메모리에 저장되는 구조로 그 사용이 간편배열은 동일한 자료 유형이 여러 개 필요한 경우에 이용할 수 있는 자료 구조크기배열의 선언은 다음과 같은 구문을 이용주요 요소는 배열 변수명(이름), 자료형, 그리고 배열의 크기배열이름 score 로 정수 int 형의 저장 공간이 메모리에 연속적으로 할당된다.
  • 38.
    배열 선언Declaration ofan array:type arrayName[ arraySize ];Exampleint 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 AnArray)배열의특정한 원소(혹은 위치)를 참조하려면 다음을 명시하여야 함Name of the array (배열 이름)Index of the element (원소 인덱스) : 0 이상 값의 정수 혹은 정수 수식첫 번째 원소의 인덱스는 0ExampleC[0] += 2;C[a + b] = 3;39
  • 40.
    Example40An array chas 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.Examplesint 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 elementsDeclare array, specify number of elementsUse repetition statement to loop for each elementExample:int n[10]; for ( int i = 0; i < 10; i++) { n[ i ] = 0; }42
  • 43.
    배열 이용Usually usefor loop to access each element of an array. C++ has no array boundary checkingReferring 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 1Example: 배열 원소들의 합 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.
  • 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구조체 정의와 변수선언과의 관계구조체 정의 구조체 변수 선언idp1struct studentnameiddeptnamep2deptidname자료구조 정의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(){structpoint 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는 같다.\n";
  • 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;}
  • 56.
  • 57.
    프로그래밍에서의 함수왜 함수를사용하는가?프로그래밍 설계 전략Divide-and-Conquer어떤 문제를 해결하기 위해 여러 개의 작은 문제로 쪼개는 것.사람이 일을 처리하는 방법도 비슷프로그램의 작성이 용이반복적인 일을 수행하는 경우 원시파일의 크기를 줄일 수 있음.
  • 58.
    함수 유형라이브러리 함수라이브러리함수는 이미 정의되어 있고 컴파일되어 있음표준 라이브러리 헤더 파일에서 원형을 제공함수의 원형(prototype)에 맞게 호출사용자 정의 함수사용자가 직접 함수 작성main도 사용자 정의 함수
  • 59.
    함수 정의프로그램은 하나이상의 함수로 구성됨
  • 60.
  • 61.
    함수정의의 일반적인 형식{ declarations statements }인자(parameter) 리스트 이 함수가 가지는 인자의 목록
  • 62.
    이 함수를호출할 때에는 이 리스트에 맞게 호출해야함 이것이 void이면 인자를 갖지 않음을 나타냄반환형(return type)함수가 반환하는 값의 자료형
  • 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.
    return 문장 return문(1) 형식 return 식;의미 - 함수 결과로서 식의 값을 반환하고 함수를 빠져나간다. (2) 형식 return;함수의 반환형이 void의미 - 이 문장을 수행하면 함수를 빠져나간다.함수의 수행 중 마지막을 만나면 함수를 빠져나간다. – return 문장의 수행과 동일한 효과 함수의 인자(parameter)인자(parameter)
  • 66.
  • 67.
    실제인자 (actual parameter) - 함수 사용에 있는 인자형식인자 (formal parameter) - 함수 정의에 있는 인자
  • 68.
    함수작성 예Task: writeExchangeValue 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; 63Should print out: x=20 y=10
  • 69.
    C/C++ functionvoid ExchangeValue(inta, 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;}64a,b: formal parameters올바르게 동작하느냐? Call by value: A copy of the value of myInterger1 and myInterger2 are passed to ExchangeValue.actual parameters
  • 70.
    C++ Tips65CALLINGBLOCKFUNCTION CALLEDPass-by-value sends a copyof the value of the actual parameterSO, the actual parameter cannot be changed by the function
  • 71.
    C++ Tips66CALLINGBLOCKFUNCTION CALLEDPass-by-reference sends the location(memory address) of the actual parameterthe actual parameter can be changed by the function
  • 72.
    Call-by-referenceGood for performancereason: eliminate copying overheadCalled the same way as call-by-valueint squareByValue (int x);int squareByReference (int & x);int x,z;…squareByValue(x);squareByReference(z);Bad for security: called function can corrupt caller’s dataSolution: use const quantifier67
  • 73.
    C/C++ function: callby referencevoid 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;}68a,b: formal parameters제대로동작함!actual parameters
  • 74.
    Passing Arrays asParametersIn 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 functionExample:// prototype float SumValues (float values [], int numOfValues );69
  • 75.
    constarray parameter Ifthe 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 );70If 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
  • 77.
  • 78.
    Pointer VariableA variablewhose value is the address of a location in memoryi.e., a variable that points to some address in memory…type * pointer_variable_name;73int* intPointer
  • 79.
    Assign Value toPointer74int alpha;int* intPointer;intPointer = &alpha;If alpha is at address 33, memory looks like thisalpha
  • 80.
    Pointer Types75 2000 12 x3000 2000 ptrint 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 points76 2000 12 x3000 2000 ptrint x; x = 12; int* ptr; ptr = &x; std::cout << *ptr;*ptr is the value in the place to which ptr points
  • 82.
    77Pointer: Dereference Operator(*) 2000 12 5 x3000 2000 ptrint x; x = 12; int* ptr; ptr = &x; *ptr = 5;// changes the value // at adddress ptr to 5
  • 83.
    Pointer Types78char 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 ch5000 6000 4000 4000 q p
  • 84.
    79intPtrmoneyPointer TypesAll pointervariables should be initialized to be NULLA pointer that points to nothing; available in <cstdlib>NULL is defined to be 0;But NULL is not memory address 0int * intPtr = NULL;Float * money = NULL;
  • 85.
    Review: lifetime ofvariables or objectsGlobal variables/objects: start from before the program starts until main() endsint 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/blockDynamical variables/objects: created using new(), malloc() callsRemains alive until delete() is called to free the memoryDestroyed upon the program exits80
  • 86.
    Dynamic allocation (newoperator)Allocation of memory space for a variable at run time (as opposed to static allocation at compile time)81int * intPointer;intPointer = new int;
  • 87.
    Deallocate allocated memoryDynamicallyallocated memory needs to be deallocated when it’s no more usedOtherwise, memory leak will degrade performancedelete operator returns memory to system delete p;Value of p is unchanged, i.e. pointing to a deallocated memoryAccessing 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 important82
  • 88.
    Pointers: examplesFigure 4-3(a)Declaring pointer variables; (b) pointing to statically allocated memory; (c) assigning a value;(d) allocating memory dynamically; (e) assigning a value83
  • 89.
    Pointers: example (cont’d)84Thismemory space cannot be deallocated, as we don’t have a pointer …
  • 90.
    Dynamically Allocated ArraysUsenew operator to allocate an array dynamicallyint arraySize; //ask user to enter arraySize… //double *anArray = new double[arraySize];arraySize has a value determined at run timeDynamically allocated array can be increaseddouble *oldArray = anArray; anArray = newdouble[2*arraySize]; // copy from oldArray to anArray delete [] oldArray; // deallocate oldArray85
  • 91.
  • 92.
    Let’s focus on:DataData: the representation of information in a manner suitable for communication or analysis by humans or machinesData are the nouns of the programming world: The objects that are manipulatedThe information that is processedDifferent view about dataApplication 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 Addresspointer referenceC++ Built-In Data TypesSimpleComposite IntegralFloatingarray struct union classchar short int long enumfloat double long double
  • 94.
    Using C/C++ DataTypeAs a C/C++ programmer, we know Based on the application, we model them as different “variables”Age: integerGender: enumerationName: array of char, or stringAlso we know what kind of operations each data type supportsWe do not worry about how an integer is implementedUnless in computer organization class …89
  • 95.
    C++ programmer areuser of int90TYPE intRepresentation of int as 16 bits two’s complement +Implementation of OperationsValue range: INT_MIN . . INT_MAX Operations: + prefix - prefix + infix - infix* infix / infix% infixRelational Operators infix(inside)
  • 96.
    Different Views ofDataApplication (or user) levelmodeling real-life data in a specific contextWhen to use a certain data type ?Logical (or ADT) levelabstract view of the domain and operationsWhatHow to use the data type ?Implementation levelspecific representation of the structure to hold the data items, and the coding for operationsHow to implement the data type ? 91
  • 97.
    Different Views ofData: Library ExampleApplication (or user) levelLibrary of Congress, or Baltimore County Public LibraryA 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 bookA library’s necessary functions to outside worldImplementation levelrepresentation of the structure to hold the “books” and the coding for operationsHow a specific library is implemented (how are books organized…)? 92
  • 98.
    A two-dimensional arrayAstructured 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]93Logic view of 2D array:all a C++ program needs to knowlogical levelint dataTable[10][6];
  • 99.
    Many recurrent datatypesListQueue: First In First OutOperating System: process queues, printing job queueStack: Last in First outCalling stackCompiler: to parse expressionsGraph:Model computer network….94Provide a high-level data type with these logic property
  • 100.
    Data Abstraction: theideaData Abstraction: the separation of a data type’s logical properties from its implementationUser of the data type only needs to understand its logical property, no need to worry about its implementation95LOGICAL PROPERTIES IMPLEMENTATIONWhat are the possible values? How can this be done in C++?What operations will be needed?
  • 101.
    Abstract Data Type:A logic viewAbstract Data Type is a specification ofa 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 featureTransformers (mutators): operations that change the state of one or more data values in an ADTObservers: operations that allow us to observe the state of the ADTIterators: operations that allow us to access each member of a data structure sequentiallyAbstract Data Type is implementation independent96
  • 102.
    OOP & ADTObject-orientedlanguage provide mechanism for specifying ADT and implementing ADTClassAn unstructured type that encapsulates a fixed number of data components (data members) with the functions (member functions) that manipulate thempredefined operations on an instance of a class are whole assignment and component accessClientSoftware that uses (declares and manipulates) objects (instances) of a particular class to solve some problem97
  • 103.
    Object-Oriented Programming: BasicsClassan unstructured type that encapsulates a fixed number of data components (data members) with the functions (called member functions) that manipulate themObjectAn instance of a classMethodA public member function of a classInstance variable (Data Member)A private data member of a class98
  • 104.
    Higher-Level AbstractionClass specificationAspecification of the class members (data and functions) with their types and/or parametersClass implementationThe code that implements the class functions99Why would you want toput them in separate files?
  • 105.
    Classes vs. StructsWithoutusing public and private, member functions and data areprivate by default in classes public by default in structs.Usually, there is no member functions defined in structsstruct is passive dataclass is active data100
  • 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 dayprivate : // 3 private data members int year ; int month ; int day ;} ;101101
  • 107.
    Use of C++data type classVariables 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 UsingDateType#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; }103How to dynamically create a DateType object ?103
  • 109.
    2 separate filesfor 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 memberfunctions// IMPLEMENTATION FILE (datetype.cpp)#include “datetype.h” // also must appear in client codeDateType :: 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 operator105
  • 111.
    C++ Classes: ConstructorsInvoked/called(automatically) when an object of the class is declared/createdA class can have several constructorsA default constructor has no argumentsdifferent 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 constructors106
  • 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 ;}107107
  • 113.
    C++ Classes: Destructors*Called(automatically) when an object’s lifetime endsTo free up resources taken by the object, esp. memoryEach class has one destructorIf you don’t need to free up resources, you can omit define destructor and the compiler will generate a default destructor108
  • 114.
    C++ Namespaces*A mechanismfor logically grouping declarations and definitions into a common declarative regionnamespace myNamespace { // Definitions // Declarations . . .} //end myNamespaceThe contents of the namespace can be accessed by code inside or outside the namespaceUse the scope resolution operator (::) to access elements from outside the namespaceAlternatively, the using declaration allows the names of the elements to be used directly109
  • 115.
    C++ Namespace: simpleexample*Creating a namespacenamespace smallNamespace{int count = 0;void abc();} // end smallNamespaceUsing a namespacesmallNamesapce::count=0;usingnamespace smallNamespace;count +=1;abc(); 110
  • 116.
    C++ std namespace*Itemsdeclared in the C++ Standard Library are declared in the std namespaceYou 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.
    EncapsulationJust as acapsule protects its contents, the class construct protects its data members112// 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 ProgrammingThree ingredientsin any object-oriented languageencapsulationinheritancepolymorphism113
  • 119.
    Inheritance Inheritance: Amechanism used with a hierarchy of classes in which each descendant class inherits the properties (data and operations) of its ancestor class Base classThe class being inherited fromDerived classthe class that inherits114Inheritance is an "is-a" …
  • 120.
    Overriding & PolymorphismPolymorphism:the ability to determine which of several operations with the same name (within the class hierarchy) is appropriate, either at compiling time (static binding) or run time (dynamic binding)OverridingFunction with virtual keyword in base class.
  • 121.
    Derived classes overridefunction as appropriate.
  • 122.
    An overridden functionin 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: Overriding116Each classhas a method PrintPerson.Print just prints the nameEmployee.Print prints the name and job titleManager.Print prints name, job title, and departmentPersonEmployeeManagerPrintis 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 ProgrammingInheritance andpolymorphism work together to allow programmer to build useful hierarchies of classes that can be put into a library to be reused in different applicationsExamples: 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 inC++Header files iostream and fstreamdeclare the istream, ostream,and ifstream, ofstream I/O classes.Both cin and cout are class objectsThese statements declare myInfile as an instance of class ifstream and invoke member function open. ifstream myInfile ; myInfile.open ( “A:\\mydata.dat” ) ;118