생성자 및 소멸자 기초
Coddy C++ 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨 — 104개 중 10번째.
생성자는 객체가 생성될 때 자동으로 실행되는 특별한 메서드입니다. 소멸자는 객체가 소멸될 때 실행됩니다.
기본 생성자
class Book {
private:
std::string title;
int pages;
public:
Book() {
this->title = "Unknown";
this->pages = 0;
}
};매개변수가 있는 생성자
Book(std::string title, int pages) {
this->title = title;
this->pages = pages;
}생성자 오버로딩 — 여러 개의 생성자
class Book {
private:
std::string title;
int pages;
public:
Book() {
this->title = "Unknown";
this->pages = 0;
}
Book(std::string title) {
this->title = title;
this->pages = 0;
}
Book(std::string title, int pages) {
this->title = title;
this->pages = pages;
}
};소멸자 — 객체가 소멸될 때 실행됩니다
class Book {
public:
~Book() {
std::cout << "Book destroyed" << std::endl;
}
};다양한 생성자로 객체 생성하기
Book book1; // 기본 생성자
Book book2("Harry Potter"); // 매개변수 한 개
Book book3("1984", 328); // 매개변수 두 개생성자는 반환 타입이 없으며 클래스와 동일한 이름을 가집니다. 소멸자는 ~ClassName()을 사용하며, 객체가 범위를 벗어날 때 생성된 순서의 역순으로 자동으로 호출됩니다.
챌린지
중급세 개의 오버로딩된 생성자와 소멸자를 가진 Product 클래스를 작성하세요:
- 매개변수가 3개인 생성자: name, price, stock
- 매개변수가 2개인 생성자: name, price (stock = 0)
- 기본 생성자: name = "Unknown", price = 0, stock = 0
- 소멸자:
"Destroying: <name>"를 출력합니다
치트 시트
생성자(constructor)는 객체가 생성될 때 자동으로 실행되는 특별한 메서드입니다. 소멸자(destructor)는 객체가 소멸될 때 실행됩니다.
기본 생성자(Default constructor) — 기본값으로 초기화합니다:
class Book {
private:
std::string title;
int pages;
public:
Book() {
this->title = "Unknown";
this->pages = 0;
}
};매개변수가 있는 생성자(Parameterized constructor) — 매개변수를 받습니다:
Book(std::string title, int pages) {
this->title = title;
this->pages = pages;
}생성자 오버로딩(Constructor overloading) — 서로 다른 매개변수를 가진 여러 생성자를 정의합니다:
class Book {
private:
std::string title;
int pages;
public:
Book() {
this->title = "Unknown";
this->pages = 0;
}
Book(std::string title) {
this->title = title;
this->pages = 0;
}
Book(std::string title, int pages) {
this->title = title;
this->pages = pages;
}
};소멸자(Destructor) — 객체가 소멸될 때 실행되며, ~ClassName() 형식을 사용합니다:
class Book {
public:
~Book() {
std::cout << "Book destroyed" << std::endl;
}
};서로 다른 생성자를 사용하여 객체 생성하기:
Book book1; // 기본 생성자
Book book2("Harry Potter"); // 매개변수 하나
Book book3("1984", 328); // 매개변수 두 개생성자는 클래스와 이름이 같으며 반환 형식이 없습니다. 소멸자는 객체가 범위를 벗어날 때 생성된 역순으로 자동으로 호출됩니다.
직접 해보기
#include <iostream>
#include "Product.h"
int main() {
std::string name;
int price, stock;
std::getline(std::cin, name);
std::cin >> price >> stock;
Product product1(name, price, stock);
Product product2("Keyboard", 79);
Product product3;
std::cout << "Product 1: " << product1.getName() << " - $" << product1.getPrice() << " (Stock: " << product1.getStock() << ")" << std::endl;
std::cout << "Product 2: " << product2.getName() << " - $" << product2.getPrice() << " (Stock: " << product2.getStock() << ")" << std::endl;
std::cout << "Product 3: " << product3.getName() << " - $" << product3.getPrice() << " (Stock: " << product3.getStock() << ")" << std::endl;
return 0;
}이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.