1 / 37

const keyword/ new 와 delete 연산자 / /Inheritance

const keyword/ new 와 delete 연산자 / /Inheritance. C++ 언어 5 일차 강 성 관. const( 상수 ) 멤버변수. const 멤버 변수 클래스의 멤버변수 가장 맨 앞에 const 키워드가 붙은 멤버변수 ( 예 ) const int val ; 상수 멤버 변수는 멤버초기자 (member initializer) 기호 ( : ) 를 통해서만 초기화가 가능하다 . format - 생성자 함수 : 상수 멤버변수 초기화

wade-barton
Download Presentation

const keyword/ new 와 delete 연산자 / /Inheritance

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

E N D

Presentation Transcript


  1. const keyword/new와delete연산자//Inheritance C++ 언어 5일차 강 성 관

  2. const(상수) 멤버변수 • const 멤버변수 • 클래스의 멤버변수 가장 맨 앞에 const 키워드가 붙은 멤버변수 • (예) const int val ; • 상수 멤버 변수는 멤버초기자(member initializer) 기호( : )를 통해서만초기화가 가능하다. • format - 생성자 함수 : 상수 멤버변수 초기화 • 상수 멤버 변수는 생성자를 통해서는 초기화 할 수 없다. • 상수가 아닌 일반 멤버변수도멤버초기자(member initializer)를 초기화가 가능하다.

  3. const(상수) 멤버변수의 초기화 class Person { private: char mouth[30] ; const int height ; //상수멤버변수 public: Person(int phei, char pmouth[30]) : height(phei) { //height = phei ; //compiler error...상수멤버변수이므로 strcpy(mouth , pmouth) ; }

  4. const(상수) 멤버함수 • 다음의 조건을 만족 하는 함수만 const(상수) 멤버함수로 만들 수 있다. • 멤버 변수의 값을 변경하지 않는 멤버 함수 • 멤버 함수를 const 함수로 만들면 좋은 점 • 다른 개발자가 “아, 이 함수는 멤버 변수의 값을 변경하지 않는구나”라고 생각하게 만든다. • 실수로 멤버 변수의 값을 바꾸려고 하면, 컴파일러가 오류 메시지를 통해서 알려준다. • 객체가 const 속성을 가진 경우(상수객체)에는 const(상수) 함수만 호출할 수 있다.

  5. const(상수) 멤버함수의사용(1) class Point { public: // 멤버 함수 void Print() const; // 생성자들 Point(); Point(const Point& pt); // 접근자 void SetX(int value); void SetY(int value); int GetX() const {return x;} int GetY() {return y;}//일부러 const 함수로 만들지 않음 private: int x, y; }; • Format int GetX() const { ……. } //멤버함수의 맨 뒤에 const를 넣는다.

  6. const (상수)멤버함수의 사용(2) void Area( const Point& pt) { // (0,0)과 pt 가 이루는 사각형의 면적을 구한다. int area = pt.GetX() * pt.GetY(); // Error // 결과 출력 cout << "(0, 0)과 이 점이 이루는 사각형의 면적 = " << area << "\n"; } • const(상수) 객체를 통해서 멤버 함수를 호출하는 예 • 매개변수 pt가 const 객체이지만 Point::GetX()는 const 함수이기 때문에 호출될 수 있다. • 그러나, Point::GetY() 는 const 함수가 아니기 때문에 컴파일 오류를 발생시킨다.

  7. const (상수)멤버함수의 사용(3) • 상수 멤버 함수 GetHeight( ) • const int GetHeight( ) const ; GetHeight( ) 함수가 상수멤버함수임을 표시 GetHeight( ) 함수가 반환하는 정수값을 변경하지 말라는 의미 • 상수화된 함수는 상수화되지 않은 함수의 호출을 허용하지 않을 뿐만아니라, 멤버 변수의 포인터를 리턴하는 것도 허용하지 않는다.

  8. const (상수)객체 • const (상수)객체 • 객체명 맨 앞에 const 키워드가 붙은 객체 • (예) const Person chulsu ; • 상수 객체는 상수 멤버함수만 호출 할 수 있다. • 상수 객체는 일반 멤버 함수는 호출할 수 없다. • 일반객체는 일반멤버함수와 상수멤버함수를 모두 호출 할 수 있다.

  9. 동적 메모리 이용(1) • 정적 메모리를 이용하는 방법 • 컴파일 타임에 어느 정도 메모리 공간을 사용하겠다고 정해놓고 사용하는 방법 • 예) 배열 : int array[32] ; =>메모리에 128 바이트의 일정공간 차지 • 동적 메모리를 이용하는 방법 • 실행 도중 필요한 메모리를 할당 받아서 사용하고 나중에 메모리를 다시 풀어주는 방법 • 메모리 할당 : new 연산자 이용 • 메모리 할당 후 포인터를 반환 • 메모리 해제 : delete연산자 이용 • new를 이용해서 메모리를 할당하면 반환한 포인터를 받아서 메모리를 해제 • 예) 포인터 이용

  10. 동적 메모리 이용(2) • 포인터 값이 유효하지 않은 경우 사용하지 못하도록 포인터로 선언한 변수는 0으로 초기화 해주고 delete 연산을 한 후에도 0 값을 지정해 준다. 예1) int *pvalue = 0 ; //포인터 변수 선언 pvalue = new int ; //정수 크기 메모리 할당 *pvalue = 100 ; //값 100할당 delete pvalue ; //메모리 해제 pvalue = 0 ; //포인터 변수 초기화 예2) int *pvalue = new int(100) ; //메모리 할당과 동시에 초기화 delete pvalue ; pvalue = 0 ;

  11. 동적 메모리 이용(3) • 포인터를 이용한 동적 메모리 사용은 배열과 같이 여러 개의 값을 집합으로 사용할 때 유용하게 이용. • new / delete 연산자를 이용해서 메모리를 할당 및 해제 pArray = new int[32] ; //배열 메모리 할당 pArray[0] = 100 ; //첨자 이용 *(pArray + 1) = 200 ; //포인터 연산을 이용 delete[] pArray ; //배열 메모리 해제 char *pString ; pString = new char[32] ; //pString 에 문자열 복사 delete[] pString ;

  12. new와 delete의 사용(1) • C에서 제공하는 동적 메모리의 할당 및 반납을 위한 함수 -malloc() w필요한 양 만큼의 메모리 할당 -free() w할당된 메모리의 해제 • C++에서 제공하는 편리하고 안전한 메모리 할당 및 해제 -new w메모리의 할당 wp-var = new type; -delete w메모리의 해제 wdelete p-var;

  13. new와 delete의 사용(2) • 새로운 연산자의 장점 -지정한 객체의 크기만큼 메모리를 자동으로 할당 w sizeof()가 필요 없음 -지정된 형의 포인터로 자동으로 변환 w형 지시자(type cast) 필요 없음 -new와 delete의 중복이 가능(배열의 동적 할당) -동적으로 할당된 객체의 초기화(단, 생성자 함수가 존재할 때)

  14. 예제 프로그램(1) p->set_ij(4,5); cout<<“Product is:”<<p->get_product()<<“\n”; delete p; return 0; } #include<iostream.h> class samp{ int i,j; public : void set_ij(int a, int b) { i = a; j = b; } int get_product() { return i*j; } }; main() { samp *p; p = new samp; if(!p) { // 메모리가 충분치 않으면 //NULL을 리턴 cout << “Allocation error\n”; return 1; }  Result :

  15. new와 delete의 추가기능(1) • 동적으로 할당된 객체 초기화(단, 생성자 함수가 존재할 때) -p-var = new type(initial – value); • 동적으로 할당된 배열을 만들 수 있다. -p-var = new type[size]; • 예제 프로그램 : 동적으로 할당된 객체 초기화 #include<iostream.h> class samp{ int i, j; public : samp(int a, int b) { i = a; j = b; } int get_product() { return i*j; } }  뒤에 계속

  16. new와 delete의 추가기능(2) main() { samp *p; p = new samp(6,5);// 생성자 함수 호출 if(!p) { cout << “Allocation error\n”; return 1; } cout << “Product is:” << p->get_product() << “\n”; delete p; return 0; }

  17. 예제프로그램:배열의 동적할당(1) #include<iostream.h> class samp { int i, j; public : void set_ij(int a, int b) { i = a; j = b; } ~samp() { cout << “Destroying…\n”; } int get_production() { return i*j; } }; main() { samp*p; int i;  뒤에 계속

  18. 예제프로그램:배열의 동적할당(2)  Result : p = new samp[10]; if(!p) { cout << “Allocation error\n”; return 1; } for(i=0; i<10; i++) p[i].set_ij( i, i ); for(i=0; i<10; i++) { cout << “Product [“ << i << ”] is : ”; cout << “p[i].get_product() << “\n”; } delete[] p; // 소멸자 함수 호출 return 0; }

  19. 상속성의 개요(1) -상속성(Inheritance) w하나의 객체가 다른 객체의 특성을 이어받을 수 있게 해 주는 과정 w자식 클래스는 부모클래스의 모든 특성을 상속 받고, 자기 자신의 특성을 추가시켜 정의 할 수 있다. • 상위 클래스에 있는 것은 상속 받아쓰고 상위클래스에 없는 것은 새로 만들자 생물 동물 식물 포유류 양서류 파충류 사 람 호랑이 남자 여자 그림1. 생태계 클래스

  20. 상속성의 개요(2) • 상속성 -하나의 클래스가 다른 클래스의 특성을 이어받는 것 • 용어 -기본(부모) 클래스(Base Class) w일반적인 모든 성질을 정의한다 - 파생(자식) 클래스(Derived Class) w기본 클래스의 특성을 이어 받는다 w이 클래스에서 지정하고자 하는 특성을 추가한다 포유류 • 코드의 중복 작업 최소화 • 소프트웨어의 재사용성 증대 사 람 호랑이

  21. 상속성의 개요(3) • 기본 클래스를 상속받기 위한 일반적인 형식 class derived-class-name : access-specifier base-class-name access-specifier : public,private,protected private 전용부분 전용부분 공용부분 공용부분 public 기본 클래스 (Base class) 파생 클래스 (Derived class)

  22. 상속성의 개요(4) class B { int i; public: void set_i(int n); int get_i(); }; class D : public B { int j; public: void set_j(int n); int mul(); }; • 예제

  23. 상속성의 개요(5) #include<iostream.h> class base { int i; public: void set_i(int n); int get_i(); }; void base::set_i(int n) { i = n; } int base::get_i() { return i; } class derived : public base { int j; public: void set_j(int n); int mul(); }; void derived::set_j(int n) { j = n; } int derived::mul() { return j*get_i(); // return j*i; Error!!! }  뒤에 계속

  24. 상속성의 개요(6) main() { derived ob; ob.set_i(10); ob.set_j(4); cout << ob.mul(); return 0; }

  25. 기본 클래스의 접근 제어(1) • 클래스 상속의 일반적인 형식 • 액세스(Access)속성 지정 - public : w기본 클래스의 public멤버는 파생 클래스의 public w기본 클래스의 protected멤버는 파생 클래스의 protected w기본 클래스의 private는 상속이 안됨 - protected : w기본 클래스의 public과 protected는 파생 클래스의 protected w기본 클래스의 private는 상속이 안됨 - private : w기본 클래스의 public과 protected는 파생 클래스의 private w기본 클래스의 private는 상속이 안됨

  26. 보호(protected)부분의 상속 class 클래스명{ [private:] //전용부분 …… //클래스 외부접근 불가능, 상속 불가능 protected: //보호부분 …… //클래스 외부접근 불가능, 상속가능 public: //공용부분 …… //클래스 외부접근 가능, 상속 가능 }; private 전용부분 전용부분 보호부분 보호부분 public 공용부분 공용부분 파생 클래스 (Derived class) 기본 클래스 (Base class)

  27. 간단한 파생클래스(Derived Class) main() { derived ob; ob.setx(10); // no error !! ob.sety(20); ob.showx(); // no error !! ob.showy(); return 0; } #include<iostream.h> class base { int x; public : void setx(int n) { x = n; } void showx() {cout << x << ‘\n’; } }; class derived : public base { int y; public : void sety(int n) { y = n; } void showy() { cout << y << ‘\n’; } };  Result :

  28. 액세스 규칙의 예제(1) #include<iostream.h> class base { int x; public : void setx(int n) { x = n; } void showx() {cout << x << ‘\n’; } }; class derived : private base { int y; public : void sety(int n) { y = n; } void showy() { cout << y << ‘\n’; } }; main() { derived ob; ob.setx(10); ob.sety(20); ob.showx(); ob.showy(); return 0; }  Result : error!

  29. 액세스 규칙의 예제(2) #include<iostream.h> class base { int x; public : void setx(int n) { x = n; } void showx() {cout << x << ‘\n’; } }; class derived : private base { int y; public : void setxy(int n, int m) { setx(n); y = m; } void showxy() { showx(); cout << y << ‘\n’; } }; main() { derived ob; ob.setxy(10, 20); ob.showxy(); return 0; }  Result :

  30. 보호 멤버의 사용(1) • 보호 멤버(protected member) -기본 클래스의 멤버를 비공개 멤버로 유지 -파생 클래스가 접근하는 것을 허용 -구조체와 공용체에서도 역시 사용 가능

  31. 보호 멤버의 사용(2) class derived : public base { int c; public : void setc(int n) { c = n; } void showabc() { cout << a << ‘’ << b << ‘’ << c <<‘\n’; } }; main() { derived ob; ob.setab(1,2); ob.setc(3); ob.showabc(); return 0; } #include<iostream.h> class base { protected : int a,b; public : void setab(int n, int m) { a = n; b = m; } };  Result :

  32. 보호 멤버의 사용(3) class derived : protected base { int c; public : void setc(int n) { c = n; } void showabc() { cout << a << ‘’ << b << ‘’ << c <<‘\n’; } }; #include<iostream.h> class base { protected : int a,b; public : void setab(int n, int m) { a = n; b = m; } }; main() { derived ob; ob.setab(1,2); ob.setc(3); ob.showabc(); return 0; }  Result : error!

  33. 상속시 생성자/소멸자 호출순서(1) • 생성자 호출순서 • 파생되는 순서에 따라 호출(베이스 클래스 > 파생 클래스) • 소멸자 호출순서 • 생성자의 역순으로 호출(파생 클래스 > 베이스 클래스)

  34. 상속시 생성자/소멸자 호출순서(2)

  35. 베이스 클래스 생성자 인수전달 (1) • 인수전달 • 베이스 클래스의 생성자에 인수가 전달되는 경우 • 베이스 클래스와파생클래스에 전달되는 모든 인수를 파생클래스에 전달 • 파생클래스의 생성자 정의 Format 파생 클래스의 생성자명(인수 리스트) : 베이스 클래스의생성자명(인수 리스트) { …………. }

  36. 베이스 클래스 생성자 인수전달 (2)

  37. 베이스 클래스 생성자 인수전달 (3)

More Related