클래스 생성자(Constructor)와 포인터(Pointer)
이번 포스팅에서 클래스 내부에 생성자 함수가 포함되어 있는 경우에 대하여 클래스 포인터를 다루어 보겠다.
예제 1
#include <iostream>
using namespace std;
class myclass {
private:
int a;
public:
myclass(int i) {
a = i;
}
int output_return() {
return a;
}
};
int main()
{
myclass ob(100), * p;
p = &ob;
cout << "p->output_return(): " << p->output_return() << endl;
return 0;
}
실행 결과
p->output_return(): 100
※ 객체 ob가 생성되면 자동적으로 생성자 함수가 호출되어 수행된다.
※ 클래스 포인터 p에 객체 ob의 시작 주소(&ob)가 대입된다.
※ p->output_return()과 ob.output_return()은 동일하다.
예제 2
#include <iostream>
using namespace std;
class myclass {
private:
int a;
public:
myclass(int i) {
a = i;
}
int output_return() {
return a;
}
};
int main()
{
myclass ob[3] = { 10, 20, 30 };
int n;
myclass* p;
p = ob;
for (n = 0; n < 3; n++) {
cout << p->output_return() << " ";
p++;
}
cout << endl;
return 0;
}
실행 결과
10 20 30
참고
1. 장인성 외 5인, (초보자도 쉽게 따라 할 수 있는) C++프로그래밍, 광문각, 2017.02.13
'C++ 기초 1' 카테고리의 다른 글
[C++] 3-4 함수에 클래스 객체를 call by reference로 전달 (1) | 2023.12.13 |
---|---|
[C++] 3-3 소멸자 (Destructor) 설명 및 예제 (0) | 2023.12.12 |
[C++] 3-1 클래스 생성자(Constructor) (2) | 2023.12.07 |
[C++] 2-10 클래스 객체 반환 (return) (3) | 2023.12.06 |
[C++] 2-9 함수의 객체 전달 (value 및 포인터) (1) | 2023.12.05 |