생성자와 접근 제한자
생성자(constructor)
생성자
- 객체가 인스턴스화 될 때 자동으로 호출되는 멤버 함수
- 리턴 타입이 없으며 클래스 이름과 동일
- 멤버 변수의 초기화가 주요 역할임
- 생성자를 정의하지 않으면 컴파일러에 의해 디폴트 생성자가 자동 추가됨
- 디폴트 생성자
- 매개변수가 없는 생성자
- 디폴트 생성자
#include <iostream> using namespace std; class Time { public: int hour; int minute; // 생성자 Time(int h, int m) { hour = h; minute = m; } void print() { cout << hour << ":" << minute << endl; } }; void printTime(Time t) { // call by value (reference: Time &t, address: Time *time) cout << "Time => " << t.hour << ":" << t.minute << endl; } int main() { // Time a; // 디폴트 생성자 호출 - 에러 Time b(10, 25); Time c{10, 25}; Time d = {10, 25}; // 정적 객체(할당)일 때 = 연산은 복사 입니다. c = b; // ? 복사인가 참조인가? c.hour = 3; b.print(); c.print(); d.print(); printTime(b); printTime(c); printTime(d); return 0; }
10:25
3:25
10:25
Time => 10:25
Time => 3:25
Time => 10:25
정적 할당일 때 대입 연산은 복사를 의미한다!!!
생성자 중복 정의(overload)
- 함수처럼 생성자도 오버로드 가능
- 매개변수가 달라야 함
- 함수처럼 생성자도 오버로드 가능
#include <iostream>
using namespace std;
class Time {
public:
int hour;
int minute;
Time() {
hour = 0;
minute = 0;
}
Time(int h, int m) {
hour = h;
minute = m;
}
void print() {
cout << hour << ":" << minute << endl;
}
};
int main() {
Time a;
Time b(10, 25);
a.print();
b.print();
return 0;
}
0:0
10:25
디폴트 인수를 사용하는 생성자
#include <iostream> using namespace std; class Time { public: int hour; int minute; Time(int h = 0, int m = 0) { hour = h; minute = m; } void print() { cout << hour << ":" << minute << endl; } }; int main() { Time a; Time b(10, 25); a.print(); b.print(); return 0; }
0:0
10:25
멤버 초기화 리스트
Time(int h, int m) { hour = h; minute = m; }
Time(int h, int m) : hour(h), minute(m) { }
생성자 정리 예제
#include <iostream> using namespace std; class Second { public: int sec; Second() { sec = 0; } Second(int s) { sec = s; } }; // Second second; // 디폴트 생성자 // Second second(20); // 매개변수 1개인 생성자 class Time { public: int hour; int minute; Second sec; Time() : sec(20) { //Second second(20); 과 같음 hour = 0; minute = 0; // sec.second = 20; // sec 인스턴스가 만들어진 이후에 하는 작업임. } Time(int h, int m) : hour(h), minute(m), sec(20) { // int hour(h); int minute(m); } void print() { cout << hour << ":" << minute << endl; } }; int main() { Time a; Time b(10, 25); a.print(); b.print(); return 0; }
0:0
10:25
이해하자!
소멸자(destructor)
소멸자
- ~클래스명()
- 인스턴스 변수가 메모리에서 사라질 때 자동으로 호출
- 전역변수 : 프로그램 종료시
- 지역변수 : 블럭이 끝날 때
- 동적 생성 변수 : delete 호출시
- 동적 할당된 자원의 cleanup 작업 수행
- 매개변수가 없으며 오버로드 불가능 --> 1개 만 만들 수 있음
#include <string.h> //
#include <string> // string 클래스 해더 파일
#include <iostream>
using namespace std;
class MyString {
private:
char *s; // 포인터
int size;
public:
MyString(char *c) {
size = strlen(c) + 1;
s = new char[size]; // 동적할당
strcpy(s, c);
}
~MyString() {
cout << "~MyString ... delete s" << endl;
delete[]s;
}
};
int main() {
MyString str("abcdefghijk");
}
ex04_destructor.cpp: In function 'int main()':
ex04_destructor.cpp:25:31: warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]
MyString str("abcdefghijk");
^
~MyString ... delete s
warnig은 일단 무시하자! 소멸자 실행되었다. new하면 delete 필수!
동적할당을 안한다면 소멸자는 필요없다.
'IoT 디바이스 활용 > C++' 카테고리의 다른 글
C++ - 객체 배열, 벡터 (0) | 2020.10.12 |
---|---|
C++ - 객체와 함수 (0) | 2020.10.12 |
C++ - 클래스와 객체 (0) | 2020.10.11 |
C++ - 문자열 (0) | 2020.10.11 |
C++ - 함수 (0) | 2020.10.11 |
댓글