: 객체가 생성될 때에 필드에게 초기값을 제공하고 필요한 초기화 절차를 실행하는 멤버 함수
#include <iostream>
using namespace std;
class Car {
private:
int speed;
int gear;
string color;
public:
Car() {
speed = 0;
gear = 1;
color = "white"
};
Car(int s, int g, string c) {
speed = s;
gear = g;
color = c;
};
};
외부 정의도 가능
class Car {
private:
int speed;
int gear;
string color;
public:
Car();
Car(int s, int g, string c);
};
Car::Car(){
...
}
Car::Car(int s, int g, string c) {
...
}
생성자를 정의하지 않는다면 컴파일러가 비어있는 디폴트 생성자를 자동으로 추가
:객체가 소멸될 때 자동으로 발생하는 메서드
class Car {
private:
int speed;
int gear;
string color;
public:
Car() {
speed = 0;
gear = 1;
color = "white";
cout << "생성자 호출" << endl;
};
~Car() {
cout << "소멸자 호출" << endl;
};
관련문제
백준 2535
[c++]클래스와 상속 (0) | 2021.01.26 |
---|---|
클래스의 기초 (0) | 2021.01.20 |
배열과 포인터 (0) | 2021.01.17 |