생성자

객체를 생성함과 동시에 멤버 변수를 초기화할 수 있다. 인스턴스화될 때 자동으로 호출되며,  클래스의 멤버 변수를 적절한 기본값 또는 사용자가 정의한 값을 갖는 인스턴스가 생성되는 것이다. 

 


 

1. 구현방법

class Student
{
private:
	string name;
	int englishScore;
	int mathScore;

public:

	Student(string n ,int e, int m)
	{
		name = n;
		englishScore = e;
		mathScore = m;
	}

};

일반 메서드를 작성하는 방법과 같다. 이름은 클래스 이름과 같게 설정해주면 된다.(반환 값은 없음) Student인 새로운 객체를 만들 때 name, englishscore, mathscore의 각각 해당하는 값을 할당해주면서 이 객체는 초기화된다.

 


 

2. 사용방법

1) 클래스 이름과 같아야함 2) 반환 값이없어야함

int main(void)
{
	Student a = Student("Mr.Han",100,98); // Student 생성!

}

 이렇게 해주면 끝!

	Student* st1 = new Student("han" , 100, 98);
	st1->NumberUp();

이런식으로 동적으로 생성할때도 생성자는 동작한다.


 

3. 디폴트 생성자

public:

	//Student(string n ,int e, int m) //생성자 주석.
	//{
	//	name = n;
	//	englishScore = e;
	//	mathScore = m;
	//}
};

int main(void)
{
	Student a = Student(); //매개변수 X

}

작성한 생성자가 없을때는 매가변수가 없는 기본 생성자로 인식한다. 멤버 변수들은 '0'혹은 'NULL'인 값으로 설정된다.

 


 

4. 복사생성자

매개변수의 값을 넘겨주는 일반 생성자와 다르게 객체를 넘겨 복사를 하도록 하는 생성자이다.

int number = 0;

class Student
{


private:
	string name;
	int englishScore;
	int mathScore;
	int num;

public:

	Student(string n, int e, int m)
	{
		name = n;
		englishScore = e;
		mathScore = m;
	}
	Student(const Student &st)
	{
		name = st.name;
		englishScore = st.englishScore;
		mathScore = st.mathScore;
	}
	void NumberUp()
	{
		number++;
		num = number;
	}

	void Show()
	{
		cout << "번호 " << num << "이름 " << name << "영어 " << englishScore << "수학 " << mathScore << '\n';

	}
};

int main()
{
	Student* st1 = new Student("han" , 100, 98);
	st1->NumberUp();
	Student st2(*st1);
	st2.NumberUp();
	st1->Show();
	st2.Show();

	system("pause");
}

st1을 만들고 st2를 만들때 생성자에 *st1을 넘김으로 써 st1을 그대로 복사한다. 각 Student객체는 NumberUp()으로 int number를 한개씩 증가 시켜 각각 num의 값을 다르게 넣도록 했다. 

 

소멸자

객체의 수명이 끝났다고 판단되면 이 객체를 제거하기 위한 목적으로 사용된다. 객체의 수명이 끝났을 때 자동으로 컴파일러가 소멸자 함수를 호출한다. 클래스명 앞에 '~'기호를 사용하여 작성한다. 

 


 

1. 구현방법

	~Student()
	{
		cout << "객체 소멸 \n";
	}
int main()
{
	Student* st1 = new Student("han" , 100, 98);
	st1->NumberUp();
	Student st2(*st1);
	st2.NumberUp();
	st1->Show();
	st2.Show();
	
	delete st1;
	system("pause");
}

st1은 선언한 지역이 끝날 때 메모리를 해제하기 전에 소멸자를 먼저 수행하지만, 동적으로 생성한 st2같은 경우는 delete키워드를 이용해 메모리를 해제요청하고 소멸자를 먼저 수행하도록 해야한다.

+ Recent posts