컴퓨터 언어/C++

[C++] C++ 9일차 클래스 3 생성자, 소멸자, this

훈츠 2020. 4. 9. 08:41
반응형

안녕하세요. 훈츠입니다. 금일은 클래스의 생성자와 소멸자 그리고this 키워드에 대해 정리 해보도록 하겠습니다. 


생성자 (constructor)

  • 객체가 생성될때 명시 하지 않아도, 자동으로 호출되는 함수 이다.
  • 객체를 초기화하는 함수 이다. 
  • public 속성을 가진다. 

소멸자 (destructor)

  • 객체가 소멸될때 명시 하지 않아도, 자동으로 호출되는 함수 이다.
  • 객체가 메모리 해제가 될때 호출 하는 함수 이다. 
  • 생성자와 동일하게 클래스명과 같은 이름의 함수이며, '~' 를 소멸자 앞에 붙인다. 
  • public 속성을 가진다. 
#include <iostream>
#include <fstream>
using namespace std;

class Spoint
{
protected:
	int m_nX, m_nY;
public :
	//생성자 
	Spoint() { 
		m_nX = 5; m_nY = 10;
		cout << "생성자 호출" << endl;
	}
	//소멸자
	~Spoint() { 
		cout << "소멸자 호출" << endl; 
	}
	void SetXY(int nX, int nY) { m_nX = nX; m_nY = nY; }
	void Print() {
		cout << "출력" << m_nX << '\t' << m_nY << endl;
	}
};

int main()
{
	Spoint spoint;
	spoint.Print();
}


디스 (this)

  • this는 현 객체의 메모리 주소를 나타낸다. 
  • this를 통해 멤버에 접근할 수 있다. (->)
class Spoint
{
protected:
	int m_nX, m_nY;

public :
	//생성자 
	Spoint() { 
		m_nX = 5; m_nY = 10;
		cout << "생성자 호출" << endl;
		
	}
	//소멸자
	~Spoint() { 
		cout << "소멸자 호출" << endl; 
	}
	void SetXY(int nX, int nY) { m_nX = nX; m_nY = nY; }
	void Print() {
		int m_nX = 500;
		int m_nY = 1000;
		cout << "출력" << m_nX << '\t' << m_nY << endl;
		cout << "출력" << this->m_nX << '\t' << this-> m_nY << endl;
	}

};
this-> m_nX 는 Print() 함수 밖에 선언된 변수를 가르키고 있고, 그냥 m_nX 는 Print() 함수 안에 선언된 변수를 출력하는것을 확인 할수 있습니다. 

 

반응형