[C++] class
Updated:
개요
- 클래스
- 상태와 행동으로 이루어진 설계도
- 생성자
- 객체가 생성될 때 호출되는 함수
- 디폴트 생성자
- 생성자를 정의하지 않았을 경우 자동으로 생성되는 생성자
- 생성자를 하나라도 정의하면 디폴트 생성자는 정의되지 않음
- 명시적인 디폴자 생성자 선언
Test() = default
- 생성자를 일부러 정의안한건지 잊은건지 판단 가능
- 복사 생성자
- 정의하지 않아도 디폴트 복사 생성자가 자동으로 정의되지만 얕은 복사를 하므로 깊은 복사가 필요하다면 명시적으로 정의
- 생성자에서 다른 생성자 호출 가능
- 소멸자
- 객체가 소멸될 때 호출되는 함수
- 디폴트 소멸자
- 디폴트 생성자와 동일
코드
#include <iostream>
#include <string>
using namespace std;
class Test {
private:
int i;
string s;
public:
Test() = default;
Test(int i) : Test(i, "-") { cout << "constructor call - Test(int i)" << endl; }
Test(int i, string s) : i(i), s(s) {
cout << "constructor call - Test(int i, string s)" << endl;
}
Test(const Test& t) {
cout << "copy constructor call" << endl;
this->i = t.i;
this->s = t.s;
}
//~Test() = default;
~Test() { cout << "destructor call" << endl; }
int GetI() const { return this->i; }
void SetI(int i) { this->i = i; }
string GetS() const { return this->s; }
void SetS(string s) { this->s = s; }
};
int main() {
Test t1(1);
Test t2(1, "a");
Test t3 = t2;
return 0;
}
실행 결과
constructor call - Test(int i, string s)
constructor call - Test(int i)
constructor call - Test(int i, string s)
copy constructor call
destructor call
destructor call
destructor call