생성자와 소멸자, this포인터 연습

오늘의 공부 정리(•̀ᴗ•́)و ̑̑


생성자(constructor)

  • 생성자는 주로 멤버변수의 초기화를 한다.
  • 생성자의 이름은 클래스명과 같다.
  • 클래스의 객체가 생성될 때마다 자동으로 호출된다.

생성자 예 : private멤버변수를 특정 값으로 초기화하는 생성자

#include <iostream>
using std::cout;
class cat{
private:
int age;
public:
cat(){age=1;} // 생성자 정의, cat():age(1){ }, cat():age{1}{ }
int getAge(){return age;}
void setAge(int a){age=a;}
};
int main()
{
cat happy; //happy객체가 생성되는 순간 생성자가 자동 호출됨
cout<<happy.getAge();
return 0;
}

소멸자(destructor)

  • 클래스의 객체가 소멸될 때 자동으로 호출된다.
  • 소멸자의 이름은 클래스명과 같고, 앞에 ~(tilde)를 붙인다.
  • 사용한 메모리 공간이 더 이상 불필요하게 될 때 해당 메모리를 시스템이나 다른 객체에 반납하는 용도로 많이 사용하는 함수이다.

소멸자 예 : 객체가 소멸되면서 "소멸"이라고 출력되는 소멸자

#include <iostream>
using std::cout;
class cat{
private:
int age;
public:
cat(int a){age=a;cout<<"멍\n";}
~cat(){cout<<"소멸\n";}
// 소멸자 정의
int getAge();
void setAge(int a);
}
int main()
{
cat happy(5);
cout<<"main함수 시작\n";
cout<<happy.getAge();
cout<<"\nmain함수 끝\n";
return 0;
}

this 포인터

  • this 포인터는 자동적으로 시스템이 만들어 주는 포인터
  • 객체를 통하여 멤버를 호출할 때 컴파일러는 객체의 포인터 즉 주소를 this포인터에 넣은
    다음 멤버를 호출한다.
  • 멤버함수에서 볼 때 this 포인터는 어떤 객체가 자신을 호출했는지 알고자 하는 경우
    사용한다.
  • 클래스의 멤버함수 내에서 다른 클래스에 자기 자신을 매개변수로 넘길 때 사용

this 포인터 예

#include <iostream>
using std::cout;
class cat{
private:
int age;
public:
cat(int a){ age=a;}
~cat(){cout<<"소멸";}
int getAge();
void setAge(int a);
};
int main()
{
cat happy(5);
cout<<happy.getAge();
return 0;
}

생성자와 소멸자, this 포인터를 사용한 코드

#include<iostream>
usingnamespacestd;
class cat {
private:
	string name;
	int age;
	double weight;
public:
	string getName() {
		return name;
	}
	void setName(string a) {
		this->name = a;
	}
	~cat() { cout<<"소멸"; }
	int getAge() {
		return age;
	}
	void setAge(int a) {
		age = a;
	}
	double getWeight() {
		return weight;
	}
	void setWeight(double a) {
		weight = a;
	}
	void meow()
	{
		cout<<"야옹.\n";
	}
};
int main()
{
	cat dalong;
	dalong.setName("다롱이");
	dalong.setAge(3);
	dalong.setWeight(10.6);
	cout<<"이름은"<< dalong.getName() <<"\n"<<"나이는"<< dalong.getAge() <<"\n"<<"몸무게는"<< dalong.getWeight() <<"\n";
}

모든 실습 코드는 C++프로그래밍(21-2학기)한성현교수 강의 내용 변형 및 요약 하였습니다.

좋은 웹페이지 즐겨찾기