C++ 생성자
생성자
C++의 생성자는 클래스의 개체가 생성될 때 자동으로 호출 되는 특수 메서드 입니다.
생성자를 생성하려면 클래스와 동일한 이름을 사용하고 그 뒤에 괄호를 사용합니다 ()
.
예시
class MyClass { // The class
public:
// Access specifier
MyClass() {
// Constructor
cout << "Hello World!";
}
};
int main() {
MyClass myObj; // Create an object of MyClass (this will call
the constructor)
return 0;
}
참고: 생성자는 클래스와 이름이 같으며 항상 public
이며 반환 값이 없습니다.
생성자 매개변수
생성자는 속성의 초기 값을 설정하는 데 유용할 수 있는 매개변수(일반 함수와 마찬가지로)도 사용할 수 있습니다.
다음 클래스에는 brand
, model
및 year
속성과 다른 매개변수가 있는 생성자가 있습니다. 생성자 내부에서 생성자 매개변수( brand=x
등)와 동일한 속성을 설정합니다. 클래스의 객체를 생성하여 생성자를 호출할 때 매개변수를 생성자에 전달하면 해당 속성의 값이 동일하게 설정됩니다.
예시
class Car { // The class
public: // Access specifier
string brand; // Attribute
string model; // Attribute
int year; // Attribute
Car(string x, string y, int z)
{ // Constructor with parameters
brand =
x;
model = y;
year = z;
}
};
int main() {
//
Create Car objects and call the constructor with different values
Car carObj1("BMW", "X5", 1999);
Car carObj2("Ford", "Mustang",
1969);
// Print values
cout << carObj1.brand << " "
<< carObj1.model << " " << carObj1.year << "\n";
cout <<
carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
return 0;
}
함수와 마찬가지로 생성자도 클래스 외부에서 정의할 수 있습니다. ::
먼저 클래스 내부에서 생성자를 선언한 다음 클래스 이름, 범위 확인 연산자, 생성자 이름(클래스와 동일) 을 지정하여 클래스 외부에서 정의합니다 .
예시
class Car { // The class
public: // Access
specifier
string brand; // Attribute
string model; // Attribute
int year;
// Attribute
Car(string x, string y, int z); //
Constructor declaration
};
// Constructor definition outside the
class
Car::Car(string x, string y, int z) {
brand = x;
model = y;
year = z;
}
int main() {
// Create
Car objects and call the constructor with different values
Car
carObj1("BMW", "X5", 1999);
Car carObj2("Ford", "Mustang", 1969);
// Print values
cout << carObj1.brand << " " <<
carObj1.model << " " << carObj1.year << "\n";
cout <<
carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
return 0;
}