클래스와클래스와데이터클래스와데이터추상화추상화 · • 특징: 캡슐화,...

40
C++ Programming C++ Programming C++ Programming C++ Programming C++ Programming C++ Programming C++ Programming C++ Programming 클래스와 클래스와 데이터 데이터 추상화 추상화 클래스와 클래스와 데이터 데이터 추상화 추상화 Seo Seo, Doo , Doo-ok ok [email protected] [email protected] http://www.Clickseo.com http://www.Clickseo.com

Upload: others

Post on 23-Jun-2020

2 views

Category:

Documents


0 download

TRANSCRIPT

C++ ProgrammingC++ ProgrammingC++ ProgrammingC++ ProgrammingC++ ProgrammingC++ ProgrammingC++ ProgrammingC++ Programming

클래스와클래스와 데이터데이터 추상화추상화클래스와클래스와 데이터데이터 추상화추상화

SeoSeo, Doo, Doo--okok

[email protected]@gmail.comhttp://www.Clickseo.comhttp://www.Clickseo.com

목목 차차

객체지향객체지향 프로그래밍프로그래밍

클래스와클래스와 객체객체클래스와클래스와 객체객체

2

객체지향객체지향 프로그래밍프로그래밍향향 밍밍

객체지향 언어 (Object-Oriented Language)

프로그램을 명령어의 목록으로 보는 시각에서 벗어나 여러 개의 프로그램을 명령어의 목록으로 보는 시각에서 벗어나 여러 개의

독립된 단위, 즉 “객체(Object)”들의 모임으로 파악

• 구성 요소 : 클래스, 객체, 메소드, 메시지

• 특 징 : 캡슐화, 추상화, 다형성, 상속, 인스턴스, 메시지 전달

• 객체지향 언어 : C++, JAVA, C#, Objective-C/C++ 등

인터페이스

(멤버 함수)

내부변수

3

사용자 구현자

객체지향객체지향 프로그래밍프로그래밍 (cont(cont’’d)d)향향 밍밍

객체지향 언어의 3가지 특징

객체지향 언어

캡슐화 다형성 상속성

정보 은닉 단일 상속

다중 상속

다중 정의

재정의

4

객체지향객체지향 프로그래밍프로그래밍 (cont(cont’’d)d)향향 밍밍

캡슐화 (encapsulation)

데이터와 데이터의 행동 양식을 결정하는 코드(절차)를 묶는 구조 데이터와 데이터의 행동 양식을 결정하는 코드(절차)를 묶는 구조

• 원하는 부분을 외부로부터 숨길 수 있다.

• 동작과 정보를 포함하는 블랙박스(Black Box)를 만들 수 있다.

인터페이스

데 이 터

+ 데 이 터

인터페이스

캡슐화

절 차

+

절 차

5

객체지향객체지향 프로그래밍프로그래밍 (cont(cont’’d)d)향향 밍밍

다형성 (polymorphism)

목적은 다르지만 연관성이 있는 두 가지 이상의 용도로 하나의 이름을 목적은 다르지만 연관성이 있는 두 가지 이상의 용도로 하나의 이름을

사용할 수 있게 하는 성질

• 다형성은 함수와 연산자에 모두 적용된다.

• C++에서는 ‘사용자 정의 자료형’에 대해서도 다형성으로 확장할 수 있다.

USB 인터페이스

6

객체지향객체지향 언어언어 (cont(cont’’d)d)향향

상속성 (inheritance)

하나의 객체가 다른 객체의 특성을 이어 받을 수 있는 특성 하나의 객체가 다른 객체의 특성을 이어 받을 수 있는 특성

• 하나의 객체는 일반적인 동작이나 성질들을 상속받아 자신의 특화된 동작과

성질들을 추가할 수 있다.

날 수 있는 객체

최고 고도비행 속도날개의 수

항공기새최고 고도비행 속도날개의 수

최고 고도비행 속도날개의 수

헬리콥터평균 수명탑재 무게엔진의 수

카나리아 전투기 여객기

7

독수리

카나리아

클래스와클래스와 객체객체

객체지향객체지향 프로그래밍프로그래밍

클래스와클래스와 객체객체

생성자와 소멸자

복사 생성자

선언 friend 선언

멤버 변수와 함수의 제한멤버 변수와 함수의 제한

클래스와 포인터, 배열

8

클래스와클래스와 객체객체

구조체의 아쉬움

struct _point{

int x;;

int y;

void OUTPUT(void)void OUTPUT(void){

cout << “x : “ << x << “y : “ << y << endl;

}}

};

“구조체 선언 시

데이터를 조작(접근)하는 함수도 묶을 수는 없을까?”

9

클래스와클래스와 객체객체 (cont(cont’’d)d)

클래스 (Class)

수 수 수 같은 목적을 가진 함수와 이 함수들이 사용하는 변수들을 한 곳에

모아서 관리하는 일종의 집합체(새로운 자료형)

• 변수 : 애트리뷰트 (attribute)변수 : 애트리뷰트 (attribute)

• 함수 : 메소드 (method)

클래스 = 멤버 변수 + 멤버 함수

객체 (Object)

• 클래스를 이용해서 정의된 자료형의 변수의 표현(완전한 대상체)

• 인스턴스화(instantiation) : 클래스를 기반으로 객체를 생성하는 것

10

클래스와클래스와 객체객체 (cont(cont’’d)d)

클래스 (cont’d)

#include <iostream>

using std::cout;using std::endl;

클래스 = 멤버 변수 + 멤버 함수

// 클래스 정의class Point{

// 멤버 변수int x;;int y;

// 멤버 함수void OUTPUT(void){{

cout << "x : " << x << ", y : " << y << endl;}

};

int main(void) Point{

// 객체 생성Point temp;

return 0;

Pointint x;int y;void OUTPUT();

11

}

클래스와클래스와 객체객체 (cont(cont’’d)d)

클래스 멤버 접근 제어

수 수 클래스 내의 멤버 변수 또는 멤버 함수의 접근 권한 부여

• private : 동일한 클래스의 접근만 허용(내부 접근)

• protected : 클래스와 상속받은 클래스의 접근 허용p• public : 모든 클래스에서 접근 허용(외부 접근)

public

protected

private

12

클래스와클래스와 객체객체 (cont(cont’’d)d)

프로그램 예제 : 객체를 사용한 초기화와 대입

#include <iostream>#include <iostream>

using std::cin;using std::cout;using std::endl;

class Point

“객체를 사용한 초기화나 대입은

기본적으로 구조체와 같다”

class Point{public:

int x;int y;void OUTPUT(void){{

cout << "x : " << x << ", y : " << y << endl;}

};

int main(void)( ){

Point a;a.x = 10;a.y = 20;a.OUTPUT();

Point b = a; // Point b(a);b.OUTPUT();

13

return 0;}

클래스와클래스와 객체객체 (cont(cont’’d)d)

프로그램 예제 : 클래스의 내부 접근과 외부 접근

#include <iostream>#include <iostream>

using std::cin;using std::cout;using std::endl;

Countint i;void Increment();

class Count{public:

int i;

();

void Increment(void){

i++; // 내부 접근}

};};

int main(void) // 외부 접근{

Count temp;

temp.i = 0;cout << "temp : " << temp.i << endl;

temp.Increment();cout << "temp : " << temp.i << endl;

14

cout << temp : << temp.i << endl;

return 0;}

클래스와클래스와 객체객체 (cont(cont’’d)d)

멤버 함수의 클래스 외부 정의#i l d i t#include <iostream>

using std::cout;using std::endl;

Pointint x;int y;

class Point{

int x;int y;

int y;void OUTPUT();

void OUTPUT(void);};

void Point::OUTPUT(void)void Point::OUTPUT(void){

cout << "x : " << x << ", y : " << y << endl;}

int main(void){

Point temp;

return 0;

15

return 0;}

클래스와클래스와 객체객체 (cont(cont’’d)d)

좋은 클래스의 설계

정보 은닉 정보 은닉 (Information Hiding)

• “모든 멤버 변수를 private으로 선언!!!”• 객체의 외부에서 객체의 멤버 변수에 직접 접근하지 못하게 하는 것.

• 오직 객체의 멤버 함수를 통하여 접근하도록 하는 방법

캡슐화 (Encapsulation)

• “관련 있는 데이터와 함수를 하나의 단위로 묶는 것”

class Point{

i tint x;int y;

public:void OUTPUT(void);// 다른 함수들…

};};

void Point::OUTPUT(void){

cout << "x : " << x << ", y : " << y << endl;}

16

}

생성자와생성자와 소멸자소멸자 (cont(cont’’d)d)생성생성

생성자 (Constructor)

객체의 생성과 동시에 호출되는 함수 객체의 생성과 동시에 호출되는 함수

클래스의 이름과 동일한 이름의 함수

• 반환하지도 않고, 반환되는 자료형도 선언되지 않는다.

• 생성자를 하나도 정의하지 않으면, 디폴트(default) 생성자가 자동 삽입된다.

class Point{

int x;

int y;

public:

Point() {}; // default 생성자

};

17

생성자와생성자와 소멸자소멸자 (cont(cont’’d)d)생성생성

생성자 함수이

프로그램 예제 : 생성자와 함수 다중 정의

#include <iostream>“생성자도 함수이므로

함수의 특징을 그대로 지닌다.”

#include <iostream>

using std::cout;using std::endl;

class Point{

Pointint _x;int _y;

{int _x;int _y;

public:Point() {}; Point(int x, int y){ Point();

Point(int, int);void ShowData();

{_x = x;_y = y;

}void ShowData(void){{

cout << "x : " << _x << ", y : " << _y << endl;}

};

int main(void){{

Point a;Point b(10, 20);a.ShowData();b.ShowData();

18

return 0;}

생성자와생성자와 소멸자소멸자 (cont(cont’’d)d)생성생성프로그램 예제 : 생성자와 디폴트 매개변수

#include <iostream>Point

int _x;int _y;Point(int = 0 int = 0);

#include <iostream>

using std::cout;using std::endl;

class Point{ Point(int = 0, int = 0);

void ShowData();{

int _x, _y;public:

Point(int x = 0, int y = 0){

_x = x;y y;_y = y;

}void ShowData(void){

cout << "x : " << x << ", y : " << y << endl;_ , y _y}

};

int main(void){

Point a; // Point a(0, 0);Point a; // Point a(0, 0);Point b(10, 20);a.ShowData();b.ShowData();

return 0;

19

return 0;}

생성자와생성자와 소멸자소멸자 (cont(cont’’d)d)생성생성

소멸자 (Destructor)

수 객체 소멸 시 자동적으로 호출되는 함수

• 객체 소멸 시 다양한 형태의 정리 작업 필요 시 ...

클래스 이름 앞에 ~가 붙은 형태의 함수

• 함수 다중 정의와 디폴트 매개변수 불가!!!

• 매개 변수와 반환되는 자료형은 선언되지 않는다.

• 소멸자를 하나도 정의하지 않으면, 디폴트(default) 소멸자가 자동 삽입된다.

class Pointclass Point{

int x;

int y;int y;

public:

~Point() {}; // default 소멸자

};

20

};

복사복사 생성자생성자생성생성

복사 생성자

수 자기 자신과 같은 형태의 객체를 인자로 받을 수 있는 생성자

• 디폴트 복사 생성자 : 자동으로 삽입되는 복사 생성자

• 두 객체의 멤버 변수와 멤버 변수를 복사두 객체의 멤버 변수와 멤버 변수를 복사

class Point{

int _x;int _y;

public:Point() { _x = _y = 0; }; Point(int x, int y = 0){{

_x = x;_y = y;

}Point(const Point &p) // default 복사 생성자{

_x = p.x;_y = p.y;

}};

21

};

복사복사 생성자생성자 (cont(cont’’d)d)생성생성

얕은 복사 (shallow copy)

디폴트 복사 생성자의 문제점

class PersonPerson a(20115678, “홍길동”);Pe son b a

{

int _id;

Person b = a;Person c(a);

char *_name;

public:

Person(int id, char *name);Person(int id, char name);

~Person(void);

void ShowData(void);

}; // 디폴트 복사 생성자Person(const Person &p){

id p id;

22

_id = p.id;_name = p.name;

}

복사복사 생성자생성자 (cont(cont’’d)d)생성생성프로그램 예제 : 디폴트 복사 생성자의 문제점 (1/2)

#include <iostream>Psrson

int _id;char *_name;

#include <iostream>#include <cstring>

using std::cout;using std::endl;

class PersonPerson(int, char *);~Person();void ShowData();

class Person{

int _id;char *_name;

public:Person(int id, char *name);P ( id)~Person(void);

void ShowData(void);};

Person::Person(int id, char *name){

생성자 함수 호출{

cout << "생성자 함수 호출!!!!" << endl;_id = id;

_name = new char[strlen(name)+1];strcpy(_name, name);

}}

Person::~Person(void){

cout << "소멸자 함수 호출!!!!" << endl;delete []_name;

}

23

}

복사복사 생성자생성자 (cont(cont’’d)d)생성생성프로그램 예제 : 디폴트 복사 생성자의 문제점 (2/2)

void Person::ShowData(void)

// 디폴트 복사 생성자

void Person::ShowData(void){

cout << "학번 : " << _id << ", 이름 : " << _name << endl;}

// 디폴트 복사 생성자Person(const Person &p){

_id = p.id;_name = p.name;

}

int main(void){

Person a(20115678, "홍길동");a ShowData(); }a.ShowData();

Person b = a; // 디폴트 복사 생성자 호출!!!b.ShowData();

Person c(a); // 디폴트 복사 생성자 호출!!!c.ShowData();

return 0;return 0;}

24

복사복사 생성자생성자 (cont(cont’’d)d)생성생성

깊은 복사 (Deep copy)

직접 복사 생성자를 제공

• 생성자 내에서 동적 할당을 하면, 반드시 제공되어야 한다.

Person::Person(const Person &p)class Person

{

int id;

Person::Person(const Person &p){

_name = new char[strlen(p._name)+1];int _id;

char *_name;

public:

strcpy(_name, p._name);}

Person(int id, char *name);

Person(const Person &p);

~Person(void);Person(void);

void ShowData(void);

};

25

복사복사 생성자생성자 (cont(cont’’d)d)생성생성프로그램 예제 : 깊은 복사 (1/2)

#include <iostream>

Psrsonint _id;char * name;

#include <iostream>#include <cstring>using std::cout;using std::endl;

class Person{ char _name;

Person(int, char *);Person(const Person &);~Person();

{int _id;char *_name;

public:Person(int id, char *name);Person(const Person &);P ( id)

();void ShowData();

~Person(void);void ShowData(void);

};

Person::Person(int id, char *name){

생성자 함수 호출{

cout << "생성자 함수 호출!!!!" << endl;_id = id;

_name = new char[strlen(name)+1];strcpy(_name, name);

}}

Person::Person(const Person &p) // 복사 생성자{

cout << "복사 생성자 함수 호출!!!!" << endl;_id = p._id;

name = new char[strlen(p name)+1];

26

_name = new char[strlen(p._name)+1];strcpy(_name, p._name);

}

복사복사 생성자생성자 (cont(cont’’d)d)생성생성프로그램 예제 : 깊은 복사 (2/2)

Person::~Person(void)Person::~Person(void){

cout << "소멸자 함수 호출!!!!" << endl;delete []_name;

}

void Person::ShowData(void){

cout << "학번 : " << _id << ", 이름 : " << _name << endl;}}

int main(void){

Person a(20115678, "홍길동");( , );a.ShowData();

Person b = a; // 복사 생성자 호출!!!b.ShowData();

Person c(a); // 복사 생성자 호출!!!c.ShowData();

return 0;

27

}

friend friend 선언선언

클래스에 대한 friend 선언

다른 클래스에서 private으로 선언된 영역의 접근 허용

• 단, friend 선언은 단방향성을 지닌다.

class Count{

int i;friend class f Count;friend class f_Count;

};

class f_Count_{public:

void SetCount(Count &r, int num){

r.i = num;}

};

28

};

friend friend 선언선언 (cont(cont’’d)d)

전역 함수에 대한 friend 선언

수 friend 선언을 통해서 private으로 선언된 멤버 변수의 접근 허용

class Count{{

int i;public:

Count() { i = 0; }void ShowData(void){

cout << “i : " << i << endl;}}friend void SetCount(Count &, int);

};

void SetCount(Count &r, int num) // 전역 함수

{r.i = num;

29

}

멤버멤버 변수와변수와 함수의함수의 제한제한

멤버 변수의 상수화

수 생성되는 객체마다 고유한 상수 값을 지정해 주면 좋은 경우

class Person{{

const int id;char name[12];

public:Person(int id, char * name)Person(int _id, char _name){

id = _id; // errorstrcpy(name, _name);

} 멤버 이니셜라이저}}; class Person

{const int id;char name[12];

(member initializer)

char name[12];public:

Person(int _id, char *_name) : id(_id){

t ( )

30

strcpy(name, _name);}

};

멤버멤버 변수와변수와 함수의함수의 제한제한 (cont(cont’’d)d)

const 멤버 함수

수 수 수 상수화된 멤버 함수는 멤버 변수의 값 변경 불가

class Count

{

int i;public:

Count() { i = 0; }

void ShowData(void) const{{

i++; // errorcout << “i : " << i << endl;

}

};

31

멤버멤버 변수와변수와 함수의함수의 제한제한 (cont(cont’’d)d)

static 멤버 변수

수 main 함수 호출되기 전에 메모리 공간을 할당 받고 초기화

• 객체의 멤버로 존재하지 않는다(클래스 내에서 접근할 수 있는 권한 부여).

class Count{public:

static int i;};

int Count::i = 1;

int main(){

cout << Count::i << endl;Count::i++;

C t icout << Count::i << endl;

return 0;}

32

클래스와클래스와 포인터포인터, , 배열배열,,

객체의 포인터

( ) 객체를 가리키는(참조하는) 용도로 사용되는 포인터

class Point{

int x;int y;

public:void OUTPUT(void) { cout << "x : " << x << ", y : " << y << endl; }

};};

int main(void){

Point a;Point *p = &a;

a.OUTPUT();

(*p) OUTPUT(); Point(*p).OUTPUT();p->OUTPUT();

return 0;}

int x;int y;void OUTPUT();

33

클래스와클래스와 포인터포인터, , 배열배열 (cont(cont’’d)d),,

자기 참조 포인터

( ) this는 자기 자신을 가리키는(참조하는) 용도로 사용되는 포인터

• 멤버 함수 내에서 this라는 이름의 포인터를 사용

class Pointc ass o t{

int x;int y;

public:Point *GetThis(void)

Pointint x;int y;

Point GetThis(void){

return this;}

};

Point *GetThis();

int main(){

Point *p = new Point(); // Point *p = new Point;

cout << "p : " << p << endl;cout << "this : " << p->GetThis() << endl;

return 0;}

34

}

클래스와클래스와 포인터포인터, , 배열배열 (cont(cont’’d)d),,

자기 참조 포인터 (cont’d)

class Point{

int x;“this 포인터로

멤버 변수의 이름 충돌 해결!!!”int y;

public:Point() { x = y = 0; }; Point(int x int y = 0)

멤버 변수의 이름 충돌 해결!!!

Point(int x, int y = 0){

this->x = x;this->y = y;

}Point(const Point &p){

thi

Pointint x;int y;

this->x = p.x;this->y = p.y;

}};

Poin();Point(int, int = 0);Point(const Point &);

35

};

클래스와클래스와 포인터포인터, , 배열배열 (cont(cont’’d)d),,

객체의 배열

수 클래스도 자료형의 한 종류기 때문에 배열을 생성할 수 있다.

• 객체의 배열을 정의할 때 각 객체들은 디폴트 생성자로 초기화된다.

l P i tclass Point{

int x;int y;

p blic

Point arr[3];

public:Point() { x = y = 0; }; Point(int x, int y = 0){

this >x = x;

arr[0];arr[1];arr[2];this->x = x;

this->y = y;}Point(const Point &p){

arr[2];

{this->x = p.x;this->y = p.y;

}};

36

};

클래스와클래스와 포인터포인터, , 배열배열 (cont(cont’’d)d),,

객체의 포인터 배열

( ) 객체를 가리키는(참조하는) 용도로 사용되는 포인터 배열

class Point{ Point *arr[3];{

int x;int y;

public:Point() { 0 }

o t a [3];

arr[0] = new Point();Point() { x = y = 0; }; Point(int x, int y = 0){

this->x = x;

arr[1] = new Point(10, 20);arr[2] = new Point(*arr[1]);

this->y = y;}Point(const Point &p){{

this->x = p.x;this->y = p.y;

}}

37

};

클래스와클래스와 포인터포인터, , 배열배열 (cont(cont’’d)d),,프로그램 예제 : 객체의 포인터 배열 (1/2)

#include <iostream>

Pointint x;int y;

#include <iostream>

using std::cin;using std::cout;using std::endl;

int y;

Poin();Point(int, int = 0);Point(const Point &);

class Point{

int x;int y;

public: ( );void ShowData();

public:Point(); Point(int, int = 0);Point(const Point &);void ShowData(void);

};};

Point::Point() { x = y = 0; }; Point::Point(int x, int y){

this->x = x;this >x x;this->y = y;

}Point::Point(const Point &p) {

this->x = p.x;

38

this >x p.x;this->y = p.y;

}

클래스와클래스와 포인터포인터, , 배열배열 (cont(cont’’d)d),,프로그램 예제 : 객체의 포인터 배열 (2/2)

void Point::ShowData(void)void Point::ShowData(void){

cout << "x : " << x << ", y : " << y << endl;}

int main(void){

int i;Point *arr[3];Point *arr[3];

arr[0] = new Point();arr[1] = new Point(10, 20);arr[2] = new Point(*arr[1]);arr[2] = new Point(*arr[1]);

for(i=0; i<3; i++)arr[i]->ShowData();

for(i=0; i<3; i++)delete arr[i];

return 0;

39

return 0;}

참고문헌참고문헌[1] 윤성우, “열혈강의 C++ 프로그래밍”, 프리렉, 2007.

[2] 이현창, “뇌를 자극하는 C++ 프로그래밍”, 한빛미디어, 2008.

[3] H M D it l P J D it l “C HOW TO PROGRAM 6th Editi P ti H ll 2009[3] H.M. Deitel, P. J. Deitel, “C++ HOW TO PROGRAM : 6th Edition”, Prentice Hall, 2009.

[4] Wikipedie, http://www.wikipedia.org/.

이 강의자료는 저작권법에 따라 보호받는 저작물이므로 무단 전제와 무단 복제를 금지하며,

내용의 전부 또는 일부를 이용하려면 반드시 저작권자의 서면 동의를 받아야 합니다.

C i ht © Cli k All i ht d

40

Copyright © Clickseo.com. All rights reserved.