객체를 생성할 때 호출되는 함수이며 따로 생성자를 정의하지 않으면 default로 매개변수 없는 생성자가 된다.
생성자는 반환형을 쓰지 않는다.
생성자는 클래스 안에서 초기화해주는 것이다.
그래서 따로 메인함수에서 초기화 할 필요없이 알아서 진행된다.
클래스안에서 public
과 private
를 나눌 수 있다.
private
에는 기본적으로 선언을 하고
public
에서 초기화나 다른 함수들을 선언한다.
그러면 메인에서는 public
의 함수를 호출하기만 하면된다.
class Student{
public:
Student() {
number = 1111;
name = "강효림";
adress = "서울";
}
void print(){
cout<<number<<endl;
cout<<name<<endl;
cout<<adress<<endl;
}
private:
int number;
string name;
string adress;
};
생성자에서 매개변수를 받을 수 있도록 메인에서 값을 받는다.
class Student{
public:
Student() {
number = 1111;
name = "강효림";
adress = "서울";
}
Student(int number, string name, string adress){
number = _number;
name = _name;
adress = _adress;
}
void print(){
cout<<number<<endl;
cout<<name<<endl;
cout<<adress<<endl;
}
private:
int number;
string name;
string adress;
};
int main(){
Student std = Student(1111, "강효림", "서울");
}
Student(int number, string name, string adress){
this->number = number;
this->name = name;
this->adress = adress;
}
this를 사용하면 멤버변수와 매개변수의 이름이 같아도 구별할 수 있다.