[C++ 6_2. 생성자, 소멸자, this 포인터 ]

·2022년 7월 27일
0

C++_Study

목록 보기
12/25

#220728~

#6-7. 생성자(Constructor) 1

  • 생성자(constructor)와 소멸자(destructor)는 꼭 정의하지 않아도 되는 함수이다.
  • 객체가 10번 생성되면 소멸자도 10번 등장
// 클래스 개 (클래스 선언)
Class Dog {
};
//객체 해피 (객체 정의) 	=> 생성자 : 보통 멤버변수 초기화하는 용도로 사용

int main(){
Dog happy;		//happy객체가 생성되는 순간 생성자가 자동 호출
return 0;
}
//객체 해피 소멸 			 => 소멸자

#6-8. 생성자2

  • 생성자와 소멸자
class Dog{
private:
    // int age = 1;
    int age;
public:
    Dog() : age(1) {} //생성자의 정의 Dog():age(1){}
    // Dog(){age=1;}                           //생성자 정의, Dog():age(1){ }
    int getAge(){return age;}
    void setAge(int a) {age = a;};
};
int main()
{
    Dog happy;                                  //happy 객체가 생성되는 순간 생성자가 자동호출됨
    std::cout << happy.getAge() << " " << std::endl;
    return 0;

#6-9. c++에서 변수를 초기화하는 방법 3가지

  • c++에서 변수를 초기화하는 방법, 생성자의 매개변수로 멤버변수 초기화
1. Dog(int a){
	age = 1;}
2. Dog(int a):age{a}{}
class Dog
{
private:
    int age;

public:
Dog(int a){
    age =a;}

int getAge() {return age;}
void setAge(int a) {age = a;}
};

int main()
{	
    Dog coco(3);            //3은 생성자로 넘어감 
    // Dog coco{3};         //Uniform initialization
    // Dog coco = Dog(2);   //비추
    // Dog coco = 1;        //비추
    
    std::cout << coco.getAge() << std::endl;
    return 0;
}

#6-10. 멤버변수로 포인터를 사용하는 경우

  • destructor: ~X()
  • copy constructor: X(const X&)
  • copy assignment: operator=(const X&) //연산자 중첩
  • move constructor: X(X&&)
  • move assignment: operator=(X&&)

#6-11. 소멸자(destructor)

: 메모리 해제하거나 할 때 사용!

  • 객체가 소멸될 때 자동으로 호출됨.
  • 소멸자의 이름은 클래스명과 동일하고 앞에 ~ 를 붙인다.
    ex). 클래스명:Dog, 소멸자 이름:~Dog()
  • 리턴형과 매개변수가 없다! (void 지정안해도 됨)
  • 사용자가 직접 호출할 수 없다.

#6-12. this 포인터

this 포인터: 자동적으로 시스템이 만들어주는 포인터

  • 객체를 통해 멤버를 호출할 때 컴파일러는 객체의 포인터 즉 주소를 this 포인터에 넣은 다음 멤버 호출함!
  • this 포인터는 멤버를 호출한 객체의 const 포인터이다
  • 멤버함수에서 볼 떄 this 포인터는 어떤 객체가 자신을 호출했는지 알고자 하는 경우 사용
class Dog
{
private:
    int age;
public:
// this -> (현재 객체), happy의 주소로 가서 그 주소에 있는 age를 넣어라 
Dog(int a);                               //{this -> age=a;}
    ~Dog();
    int getAge();
    void setAge(int a);
};

Dog::Dog(int a)
{
    age=a;
    // happy와 meri의 객체의 주소 출력 (this)
    std::cout << this << std::endl;
}

Dog::~Dog()
{
    std::cout << "소멸" << std::endl; 
}
int Dog::getAge()
{
    return age;
}
void Dog::setAge(int a)
{
    age=a;
}

int main()
{   
    Dog happy(5), meri(3);
    std::cout << happy.getAge() << std::endl;
    std::cout << meri.getAge() << std::endl;
    return 0;
}

  • Cat 객체 실습
  • Cat 클래스 구현

    • 나이, 몸무게, 이름을 private 멤버변수로 갖고 이것들을 매개변수로 받아들여

    • 초기화 할 수있는 생성자와 "소멸"이라고 출력하는 소멸자를 갖는다.

    • private 멤버변수에 접근(입/출력) 하기 위한 범용 접근자 함수(getXX, setXX)구현

    • 고양이의 특성을 나타내는 멤버함수도

    • this 포인터도 사용

class Cat {
private:
    int age;
    char name[20];
    //const char* name;                 //A
public:
    Cat(int age, const char* n){
        this->age = age;
        strcpy(name,n);     //name=n;   //A
        std::cout << name << "고양이 객체가 만들어졌어요.\n";
    }
~Cat() {std::cout << name << "객체 바이\n";}

int getAge(); 
const char* getName();
void setAge(int age);
void setName(const char* pName);
void meow();
};

int Cat::getAge(){
    return age;
}
void Cat::setAge(int age){
    this ->age = age;
}
void Cat::setName(const char* pName){
    strcpy(name, pName);
    //name=pName;           //A
}
const char* Cat::getName(){
    return name;
}
void Cat::meow(){
    std::cout << name << "고양이가 울어요\n" << std::endl;
}


int main() {
    Cat nabi(1,"나비"), yaong(1,"야옹이"), *pNabi;
    
    std::cout << nabi.getName() << "출생 나이는" << nabi.getAge() << "살이다.\n" <<std::endl;
    std::cout << yaong.getName() << "출생 나이는" << yaong.getAge() << "살이다.\n" <<std::endl;
    
    pNabi = &nabi;
    std::cout << pNabi -> getName() << "출생 나이는" << pNabi->getAge() << "살이다.\n" <<std::endl;
    nabi.setName("Nabi");
    
    nabi.setAge(3);
    std::cout << nabi.getName() << "출생 나이는" << pNabi->getAge() << "살이다.\n"<< std::endl;
    yaong.meow();
    nabi.meow();
    return 0;
    
}

// 결과값 
나비고양이 객체가 만들어졌어요.
야옹이고양이 객체가 만들어졌어요.
나비출생 나이는1살이다.
야옹이출생 나이는1살이다.
나비출생 나이는1살이다.
Nabi출생 나이는3살이다.
야옹이고양이가 울어요
Nabi고양이가 울어요
야옹이객체 바이
Nabi객체 바이
profile
Hakuna Matata

0개의 댓글

관련 채용 정보