출처 :
- 명품 C++ Programming (저자 황기태)
- 객체지향프로그래밍
객체 포인터
- 객체의 주소 값을 가지는 변수
- 포인터로 멤버를 접근할 때 . 연산자 대신 - > 객체포인터 - > 멤버
| Circle donut; |
| double d = donut.getArea(); |
| |
| |
| Circle *p; |
| p = &donut; |
| d = p -> getArea(); |
*포인터로도 private 에는 접근 불가능
| p->getArea() == (*p).getArea() |
| |
객체 배열, 생성 및 소멸
객체 배열 선언
- 객체 배열을 위한 공간 할당
- 배열의 각 원소 객체마다 생성자 실행
*매개 변수 없는 생성자를 선언하지 않았다면 매개 변수 있는 생성자도 선언하지 않아야 자동으로 매개 변수 없는 생성자가 생성된다.
| class Circle { |
| int radius; |
| public: |
| Circle(int r) { radius = r; } |
| double getArea() { |
| return 3.14 * radius * radius; |
| } |
| }; |
| |
| int main() { |
| Circle waffle(15); |
| Circle circleArray[3]; |
| } |
| Circle *p; |
| p = circleArray; |
| |
| for (int i = 0; i < 3; i++) { |
| cout << "Circle" << i << "의 면적은 " << circleArray[i].getArea() << endl; |
| |
| cout << "Circle" << i << "의 면적은 " << p->getArea() << endl; |
| p++; |
| } |
객체 배열 생성 및 소멸
선언
- 객체 배열을 위한 공간 할당
- 배열의 각 원소 객체마다 생성자 실행
- c[0]의 생성자, c[1]의 생성자...
- c[0][0], c[0][1], c[1][0] ... 순서
- 매개 변수 없는 생성자 호출 (매개 변수 있는 생성자 호출 불가능)
소멸
객체 배열 초기화
| Circle circleArray[3] = { Circle(10), Circle(20), Circle() }; |
| |
동적 메모리 할당 및 반환
정적 할당
- 변수 선언을 통해 필요한 메모리 할당
- 많은 양의 메모리는 배열 선언을 통해 할당
동적 할당
- 필요한 양이 예측되지 않는 경우. 프로그램 작성시 할당 받을 수 없음.
- 실행 중에 힙 메모리에 할당
- 메모리가 더 필요한 즉시 힙 heap으로부터 할당
- 힙 : 운영체제가 프로세스(프로그램)의 실행을 시작 시킬 떄 동적 할당 공간으로 준 메모리 공간
c++ 동적 메모리 할당/반환
| 데이터 타입 *포인터변수 = new 데이터타입; |
| 데이터 타입 *포인터변수 = new 데이터타입(초기값); |
| delete 포인터 변수; |
| |
| 테이터 타입 *포인터변수 = new 데이터타입 [배열의 크기]; |
| |
| delete [] 포인터 변수; |
| int *pInt = new int; |
| Circle *pCircle = new Circle(); |
| |
| delete pInt; |
| delete pCircle; |
| #include <iostream> |
| using namespace std; |
| |
| int main() { |
| int *p; |
| |
| p = new int; |
| |
| if (!p) { |
| cout << "메모리 할당할 수 없음"; |
| return 0; |
| } |
| |
| *p = 5; |
| int n = *p; |
| |
| delete p; |
| }; |
객체 배열의 사용, 배열의 반환과 소멸자
| |
| Circle *pArray = new Circle[3]; |
| |
| pArray[0].setRadius(10); |
| pArray[1].setRadius(20)' |
| pArray[2].setRadius(30)' |
| |
| for (int i = 0; i < 3; i++ |
| cout << pArray[i].getArea(); |
| |
| |
| pArray->setRadius(10); |
| (pArray+1)->setRadius(20); |
| (pArray+2)->setRadius(30); |
| |
| |
| delete [] pArray; |
| |
예제 정수형 배열의 동적 할당 및 반환
| #include <iostream> |
| using namespace std; |
| |
| int main() { |
| int n; |
| cin >> n; |
| |
| if (n <= 0) return 0; |
| |
| int *p = new int[n]; |
| if (!p) { |
| cout << "메모리를 할당할 수 없습니다."; |
| return 0; |
| } |
| |
| for (int i = 0; i < n; i++) { |
| cout << i + 1 << "번째 정수 : "; |
| cin >> p[i]; |
| } |
| |
| int sum = 0; |
| for (int i = 0; i < n; i++) |
| sum += p[i]; |
| cout << "평균 = " << sum / n << endl; |
| |
| delete [] p; |
| } |
동적 메모리 할당과 메모리 누수
| char n = 'a'; |
| char *p = new char[1024]; |
| p = &n; |
| |
| |
this 포인터
- 포인터, 객체 자신 포인터
- 클래스의 멤버 함수 내에서만 사용
- 개발자가 선언하는 변수가 아닌 컴파일러가 선언한 변수
- 멤버 함수에 컴파일러에 의해 묵시적으로 삽입되는 매개 변수
- 각 객체 속의 this는 다른 객체의 this와 다름
| class Circle { |
| int radius; |
| public: |
| Circle() { this->radius=1; } |
| void setRadius(int radius) { this->raadius = radius; } |
| |
this 가 필요한 경우
- 매개변수의 이름과 멤버 변수의 이름이 같은 경우
| Circle (int radius) { |
| this->radius = radius; |
| } |
| class Sample { |
| public: |
| Sample * f() { |
| ... |
| return this; |
| } |
| } |
this의 제약 사항
- 멤버 함수가 아닌 함수에서 this 사용 불가 - 객체와의 관련성이 없음
- static 멤버 함수에서 this 사용 불가 객체가 생기기 전에 static 함수 호출이 있을 수 있기 때문
this 포인터의 실체 - 컴파일러에서 처리
| |
| class Sample { |
| int a; |
| public: |
| void setA(int x) { |
| this->a = x; |
| } |
| }; |
| |
| |
| class Sample { |
| ... |
| public: |
| void setA(Sample *this, int x) { |
| this->a = x; |
| } |
| }; |
| |
| |
| ob.setA(5); |
| ob.setA(&ob, 5); |
| |
String 클래스를 이용한 문자열
C++ 문자열
- C- 스트링
- C++ string 클래스의 객체
String 클래스
- <string> 헤더파일에 선언
- 가변크기의 문자열
- 문자열 복사, 문자열 비교, 문자열 길이 등 다양한 문자열 연산자와 멤버 함수 포함
- 문자열, 스트링, 문자열 객체, string 객체 등으로 혼용
문자열 생성
| string str; |
| string address("블라블라"); |
| string copyAdress(address); |
| char text[] = {'L','O','V','E','\\0'}; |
| string title(text); |
문자열 숫자 변환 stoi() 함수 이용
| string s = "123"; |
| int n = stoi(s); |
string 객체의 동적 생성
new/delete를 이용하여 문자열을 동적 생성/반환 가능
| string *p = new string("C++"); |
| |
| cout << *p; |
| p->append(" Great!!"); |
| |
| delete p; |
예제 - string 배열 선언과 문자열 키 입력 응용
| #include <iostream> |
| #include <string> |
| using namespace std; |
| |
| int main() { |
| string names[5]; |
| |
| for (int i = 0; i < 5; i++) { |
| cout << "이름 >> "; |
| getline(cin, names[i], '\\0'); |
| } |
| |
| string latter = names[0]; |
| for (int i = 1; i < 5; i++ ) |
| if (latter < names[i]) |
| latter = names[i]; |
| } |
| |
밑에 예제 더 있음~~!! ppt 39 부터