도순씨의 코딩일지
C++ :: 클래스와 배열, this 포인터 본문
C++의 구조체 배열은 C언어와 유사한 면이 많습니다.
🌼 객체 배열
객체 기반 배열은 다음과 같은 형태로 선언합니다.
1
|
SoSimple arr[10];
|
cs |
동적으로 할당하는 경우에는 다음과 같은 형태로 선언합니다.
1
|
SoSimple * ptrArr = new SoSimple[10]
|
cs |
이러한 형태를 선언하면 열 개의 SoSimple 객체가 모여 배열을 구성합니다. 배열 선언을 하는 경우에도 생성자는 호출이 됩니다. 단, 배열의 선언 과정에서는 호출 생성자를 별도로 명시하지 못합니다.
따라서 원하는 값으로 초기화하고 싶다면 초기화의 과정을 별도로 거쳐야 합니다. 다음 예제를 살펴보도록 합시다.
⭐️ ObjArr.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
|
#include <iostream>
#include <cstring>
using namespace std;
class Person{
private:
char *name;
int age;
public:
Person(char * myname, int myage){
int len = strlen(myname) + 1;
name = new char[len];
strcpy(name, myname);
age = myage;
}
Person(){
name = NULL;
age = 0;
cout << "called Person()"<<endl;
}
void SetPersonInfo(char * myname, int myage){
name = myname;
age = myage;
}
void ShowPersonInfo() const{
cout << "이름: " << name << ", ";
cout << "나이: " << age << endl;
}
~Person(){
delete []name;
cout << "called destructor!"<< endl;
}
};
int main(void){
Person parr[3];
char namestr[100];
char * strptr;
int age;
int len;
for(int i = 0 ; i < 3 ; i++){
cout << "이름: ";
cin >> namestr;
cout << "나이: ";
cin >> age;
len = strlen(namestr) + 1;
strptr = new char[len];
strcpy(strptr, namestr);
parr[i].SetPersonInfo(strptr, age);
}
parr[0].ShowPersonInfo();
parr[1].ShowPersonInfo();
parr[2].ShowPersonInfo();
return 0;
}
|
cs |
⭐️ 실행 결과
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
called Person()
called Person()
called Person()
이름: 도순
나이: 20
이름: 슬기
나이: 20
이름: 아이린
나이: 21
이름: 도순, 나이: 20
이름: 슬기, 나이: 20
이름: 아이린, 나이: 21
called destructor!
called destructor!
called destructor!
|
cs |
🌼 객체 배열
객체 배열에 객체로 이뤄진 배열이라면, 객체 포인터 배열은 객체의 주소 값 저장이 가능한 포인터 변수로 이뤄진 배열입니다.
⭐️ ObjPtrArr.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
|
#include <iostream>
#include <cstring>
using namespace std;
class Person{
private:
char *name;
int age;
public:
Person(char * myname, int myage){
int len = strlen(myname) + 1;
name = new char[len];
strcpy(name, myname);
age = myage;
}
Person(){
name = NULL;
age = 0;
cout << "called Person()"<<endl;
}
void SetPersonInfo(char * myname, int myage){
name = myname;
age = myage;
}
void ShowPersonInfo() const{
cout << "이름: " << name << ", ";
cout << "나이: " << age << endl;
}
~Person(){
delete []name;
cout << "called destructor!"<< endl;
}
};
int main(void){
Person *parr[3];
char namestr[100];
int age;
for(int i = 0 ; i < 3 ; i++){
cout << "이름: ";
cin >> namestr;
cout << "나이: ";
cin >> age;
parr[i] = new Person(namestr, age);
}
parr[0] -> ShowPersonInfo();
parr[1] -> ShowPersonInfo();
parr[2] -> ShowPersonInfo();
delete parr[0];
delete parr[1];
delete parr[2];
return 0;
}
|
cs |
⭐️ ObjPtrArr.cpp 실행 결과
1
2
3
4
5
6
7
8
9
10
11
12
|
이름: 태연
나이: 32
이름: 윤아
나이: 31
이름: 효연
나이: 32
이름: 태연, 나이: 32
이름: 윤아, 나이: 31
이름: 효연, 나이: 32
called destructor!
called destructor!
called destructor!
|
cs |
🌼 this 포인터
멤버함수 내에서는 this라는 이름의 포인터를 사용할 수 있습니다. 이는 객체 자신을 가리키는 용도로 사용됩니다. 간단한 예제를 통해서 this 포인터를 알아보도록 합시다.
⭐️ PointerThis.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
#include <iostream>
#include <cstring>
using namespace std;
class SoSimple{
private:
int num;
public:
SoSimple(int n) : num(n){
cout << "num=" << num << ", ";
cout << "address = "<<this<<endl;
}
void ShowSimpleData(){
cout << num << endl;
}
SoSimple * GetThisPointer(){
return this;
}
};
int main(void){
SoSimple sim1(100);
SoSimple * ptr1 = sim1.GetThisPointer(); // sim1 객체의 주소 값 저장
cout << ptr1 << ", ";
ptr1 -> ShowSimpleData();
SoSimple sim2(200);
SoSimple * ptr2 = sim2.GetThisPointer();
cout << ptr2 << ", ";
ptr2 -> ShowSimpleData();
return 0;
}
|
cs |
⭐️ PointerThis.cpp 실행결과
1
2
3
4
|
num=100, address = 0x7ffee2694878
0x7ffee2694878, 100
num=200, address = 0x7ffee2694868
0x7ffee2694868, 200
|
cs |
this는 객체 자신의 주소를 의미한다는 것을 알 수 있습니다. this 포인터는 유용하게 사용되는데, 먼저 다음 클래스를 살펴봅시다.
1
2
3
4
5
6
7
8
9
|
class ThisClass{
private:
int num; // 207이 저장됨
public:
void ThisFunc(int num){
this -> num = 207;
num = 105; // 매개변수의 값을 105로 변경함
}
};
|
cs |
변수의 이름만을 참조하는 방법으로는 num에 접근이 불가능합니다. 그러나 this 포인터를 활용하면 접근 가능합니다.
다른 예제를 또 살펴보도록 해봅시다.
⭐️ UsefulThisPtr.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
#include <iostream>
using namespace std;
class TwoNumber{
private:
int num1, num2;
public:
TwoNumber(int num1, int num2){
this -> num1 = num1;
this -> num2 = num2;
}
/*
TwoNumber(int num1, int num2) : num1(num1), num2(num2){}
*/
void ShowTwoNumber(){
cout << this -> num1 << endl;
cout << this -> num2 << endl;
}
};
int main(void){
TwoNumber two(2, 4);
two.ShowTwoNumber();
return 0;
}
|
cs |
⭐️ 실행결과
1
2
|
2
4
|
cs |
멤버 이니셜라이저에서는 this 포인터를 사용할 수 없습니다.
🌼 Self-Reference의 반환
Self-Reference란 객체 자신을 참조할 수 있는 참조자를 의미합니다. 다음 예제를 봅시다.
⭐️ SelfRef.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
#include <iostream>
using namespace std;
class SelfRef{
private:
int num;
public:
SelfRef(int n) : num(n){
cout << "객체설정" << endl;
}
SelfRef& Adder(int n){
num += n;
return *this;
}
SelfRef& ShowTwoNumber(){
cout << num << endl;
return *this;
}
};
int main(void){
SelfRef obj(3);
SelfRef &ref = obj.Adder(2);
obj.ShowTwoNumber();
ref.ShowTwoNumber();
ref.Adder(1).ShowTwoNumber().Adder(2).ShowTwoNumber();
return 0;
}
|
cs |
⭐️ 실행 결과
1
2
3
4
5
|
객체설정
5
5
6
8
|
cs |
📜 출처
윤성우(2010). 윤성우 열혈 C++ 프로그래밍. 오렌지미디어.
'𝐏𝐑𝐎𝐆𝐑𝐀𝐌𝐌𝐈𝐍𝐆 > 𝐂++' 카테고리의 다른 글
C++ :: const, friend 키워드 (0) | 2020.08.16 |
---|---|
C++ :: 복사 생성자(Copy Constructor) (0) | 2020.08.16 |
C++ :: 생성자(Constructor)와 소멸자(Destructor) (0) | 2020.08.15 |
C++ :: 캡슐화(Encapsulation) (0) | 2020.08.14 |
C++:: 정보은닉(Information Hiding) (0) | 2020.08.14 |