logo

C++ 생성자

C++에서 생성자는 객체 생성 시 자동으로 호출되는 특수 메서드입니다. 일반적으로 새 객체의 데이터 멤버를 초기화하는 데 사용됩니다. C++의 생성자는 클래스 또는 구조체와 이름이 동일합니다.

간단히 말해서, C++에서 객체가 생성될 때 생성자라는 특정 프로시저가 자동으로 호출됩니다. 일반적으로 새로운 사물의 데이터 멤버를 생성하는 데 사용됩니다. C++에서는 클래스 또는 구조체 이름이 생성자 이름으로도 사용됩니다. 객체가 완성되면 생성자가 호출됩니다. 사물에 대한 값을 생성하거나 데이터를 제공하므로 생성자라고 합니다.

생성자 프로토타입은 다음과 같습니다.

 (list-of-parameters); 

다음 구문은 클래스 생성자를 정의하는 데 사용됩니다.

 (list-of-parameters) { // constructor definition } 

다음 구문은 클래스 외부에서 생성자를 정의하는 데 사용됩니다.

파이썬은 바이트를 문자열로 변환합니다.
 : : (list-of-parameters){ // constructor definition} 

생성자에는 반환 값이 없으므로 반환 유형이 없습니다.

C++에는 두 가지 유형의 생성자가 있을 수 있습니다.

  • 기본 생성자
  • 매개변수화된 생성자

C++ 기본 생성자

인수가 없는 생성자를 기본 생성자라고 합니다. 객체 생성시 호출됩니다.

C++ 기본 생성자의 간단한 예를 살펴보겠습니다.

 #include using namespace std; class Employee { public: Employee() { cout&lt;<'default constructor invoked'<<endl; } }; int main(void) { employee e1; creating an object of e2; return 0; < pre> <p> <strong>Output:</strong> </p> <pre>Default Constructor Invoked Default Constructor Invoked </pre> <h2>C++ Parameterized Constructor</h2> <p>A constructor which has parameters is called parameterized constructor. It is used to provide different values to distinct objects.</p> <p>Let&apos;s see the simple example of C++ Parameterized Constructor.</p> <pre> #include using namespace std; class Employee { public: int id;//data member (also instance variable) string name;//data member(also instance variable) float salary; Employee(int i, string n, float s) { id = i; name = n; salary = s; } void display() { cout&lt; <id<<' '<<name<<' '<<salary<<endl; } }; int main(void) { employee e1="Employee(101," 'sonoo', 890000); creating an object of e2="Employee(102," 'nakul', 59000); e1.display(); e2.display(); return 0; < pre> <p> <strong>Output:</strong> </p> <pre>101 Sonoo 890000 102 Nakul 59000 </pre> <h2>What distinguishes constructors from a typical member function?</h2> <ol class="points"> <li>Constructor&apos;s name is the same as the class&apos;s</li> <li>Default There isn&apos;t an input argument for constructors. However, input arguments are available for copy and parameterized constructors.</li> <li>There is no return type for constructors.</li> <li>An object&apos;s constructor is invoked automatically upon creation.</li> <li>It must be shown in the classroom&apos;s open area.</li> <li>The C++ compiler creates a default constructor for the object if a constructor is not specified (expects any parameters and has an empty body).</li> </ol> <p>By using a practical example, let&apos;s learn about the various constructor types in C++. Imagine you visited a store to purchase a marker. What are your alternatives if you want to buy a marker? For the first one, you ask a store to give you a marker, given that you didn&apos;t specify the brand name or colour of the marker you wanted, simply asking for one amount to a request. So, when we just said, &apos;I just need a marker,&apos; he would hand us whatever the most popular marker was in the market or his store. The default constructor is exactly what it sounds like! The second approach is to go into a store and specify that you want a red marker of the XYZ brand. He will give you that marker since you have brought up the subject. The parameters have been set in this instance thus. And a parameterized constructor is exactly what it sounds like! The third one requires you to visit a store and declare that you want a marker that looks like this (a physical marker on your hand). The shopkeeper will thus notice that marker. He will provide you with a new marker when you say all right. Therefore, make a copy of that marker. And that is what a copy constructor does!</p> <h2>What are the characteristics of a constructor?</h2> <ol class="points"> <li>The constructor has the same name as the class it belongs to.</li> <li>Although it is possible, constructors are typically declared in the class&apos;s public section. However, this is not a must.</li> <li>Because constructors don&apos;t return values, they lack a return type.</li> <li>When we create a class object, the constructor is immediately invoked.</li> <li>Overloaded constructors are possible.</li> <li>Declaring a constructor virtual is not permitted.</li> <li>One cannot inherit a constructor.</li> <li>Constructor addresses cannot be referenced to.</li> <li>When allocating memory, the constructor makes implicit calls to the new and delete operators.</li> </ol> <h2>What is a copy constructor?</h2> <p>A member function known as a copy constructor initializes an item using another object from the same class-an in-depth discussion on Copy Constructors.</p> <p>Every time we specify one or more non-default constructors (with parameters) for a class, we also need to include a default constructor (without parameters), as the compiler won&apos;t supply one in this circumstance. The best practice is to always declare a default constructor, even though it is not required.</p> <p>A reference to an object belonging to the same class is required by the copy constructor.</p> <pre> Sample(Sample &amp;t) { id=t.id; } </pre> <h2>What is a destructor in C++?</h2> <p>An equivalent special member function to a constructor is a destructor. The constructor creates class objects, which are destroyed by the destructor. The word &apos;destructor,&apos; followed by the tilde () symbol, is the same as the class name. You can only define one destructor at a time. One method of destroying an object made by a constructor is to use a destructor. Destructors cannot be overloaded as a result. Destructors don&apos;t take any arguments and don&apos;t give anything back. As soon as the item leaves the scope, it is immediately called. Destructors free up the memory used by the objects the constructor generated. Destructor reverses the process of creating things by destroying them.</p> <p>The language used to define the class&apos;s destructor</p> <pre> ~ () { } </pre> <p>The language used to define the class&apos;s destructor outside of it</p> <pre> : : ~ (){} </pre> <hr></id<<'></pre></'default>

C++ 매개변수화된 생성자

매개변수를 갖는 생성자를 매개변수화된 생성자라고 합니다. 이는 개별 개체에 다른 값을 제공하는 데 사용됩니다.

C++ 매개변수화된 생성자의 간단한 예를 살펴보겠습니다.

문자열 정수
 #include using namespace std; class Employee { public: int id;//data member (also instance variable) string name;//data member(also instance variable) float salary; Employee(int i, string n, float s) { id = i; name = n; salary = s; } void display() { cout&lt; <id<<\' \'<<name<<\' \'<<salary<<endl; } }; int main(void) { employee e1="Employee(101," \'sonoo\', 890000); creating an object of e2="Employee(102," \'nakul\', 59000); e1.display(); e2.display(); return 0; < pre> <p> <strong>Output:</strong> </p> <pre>101 Sonoo 890000 102 Nakul 59000 </pre> <h2>What distinguishes constructors from a typical member function?</h2> <ol class="points"> <li>Constructor&apos;s name is the same as the class&apos;s</li> <li>Default There isn&apos;t an input argument for constructors. However, input arguments are available for copy and parameterized constructors.</li> <li>There is no return type for constructors.</li> <li>An object&apos;s constructor is invoked automatically upon creation.</li> <li>It must be shown in the classroom&apos;s open area.</li> <li>The C++ compiler creates a default constructor for the object if a constructor is not specified (expects any parameters and has an empty body).</li> </ol> <p>By using a practical example, let&apos;s learn about the various constructor types in C++. Imagine you visited a store to purchase a marker. What are your alternatives if you want to buy a marker? For the first one, you ask a store to give you a marker, given that you didn&apos;t specify the brand name or colour of the marker you wanted, simply asking for one amount to a request. So, when we just said, &apos;I just need a marker,&apos; he would hand us whatever the most popular marker was in the market or his store. The default constructor is exactly what it sounds like! The second approach is to go into a store and specify that you want a red marker of the XYZ brand. He will give you that marker since you have brought up the subject. The parameters have been set in this instance thus. And a parameterized constructor is exactly what it sounds like! The third one requires you to visit a store and declare that you want a marker that looks like this (a physical marker on your hand). The shopkeeper will thus notice that marker. He will provide you with a new marker when you say all right. Therefore, make a copy of that marker. And that is what a copy constructor does!</p> <h2>What are the characteristics of a constructor?</h2> <ol class="points"> <li>The constructor has the same name as the class it belongs to.</li> <li>Although it is possible, constructors are typically declared in the class&apos;s public section. However, this is not a must.</li> <li>Because constructors don&apos;t return values, they lack a return type.</li> <li>When we create a class object, the constructor is immediately invoked.</li> <li>Overloaded constructors are possible.</li> <li>Declaring a constructor virtual is not permitted.</li> <li>One cannot inherit a constructor.</li> <li>Constructor addresses cannot be referenced to.</li> <li>When allocating memory, the constructor makes implicit calls to the new and delete operators.</li> </ol> <h2>What is a copy constructor?</h2> <p>A member function known as a copy constructor initializes an item using another object from the same class-an in-depth discussion on Copy Constructors.</p> <p>Every time we specify one or more non-default constructors (with parameters) for a class, we also need to include a default constructor (without parameters), as the compiler won&apos;t supply one in this circumstance. The best practice is to always declare a default constructor, even though it is not required.</p> <p>A reference to an object belonging to the same class is required by the copy constructor.</p> <pre> Sample(Sample &amp;t) { id=t.id; } </pre> <h2>What is a destructor in C++?</h2> <p>An equivalent special member function to a constructor is a destructor. The constructor creates class objects, which are destroyed by the destructor. The word &apos;destructor,&apos; followed by the tilde () symbol, is the same as the class name. You can only define one destructor at a time. One method of destroying an object made by a constructor is to use a destructor. Destructors cannot be overloaded as a result. Destructors don&apos;t take any arguments and don&apos;t give anything back. As soon as the item leaves the scope, it is immediately called. Destructors free up the memory used by the objects the constructor generated. Destructor reverses the process of creating things by destroying them.</p> <p>The language used to define the class&apos;s destructor</p> <pre> ~ () { } </pre> <p>The language used to define the class&apos;s destructor outside of it</p> <pre> : : ~ (){} </pre> <hr></id<<\'>

생성자와 일반적인 멤버 함수의 차이점은 무엇입니까?

  1. 생성자 이름은 클래스 이름과 동일합니다.
  2. 기본값 생성자에 대한 입력 인수가 없습니다. 그러나 복사 및 매개변수화된 생성자에는 입력 인수를 사용할 수 있습니다.
  3. 생성자에는 반환 유형이 없습니다.
  4. 객체 생성자는 생성 시 자동으로 호출됩니다.
  5. 교실의 공개된 공간에 보여주어야 합니다.
  6. C++ 컴파일러는 생성자가 지정되지 않은 경우(매개변수가 필요하고 본문이 비어 있는 경우) 개체에 대한 기본 생성자를 만듭니다.

실제 예제를 통해 C++의 다양한 생성자 유형에 대해 알아봅시다. 마커를 구입하기 위해 매장을 방문했다고 가정해 보세요. 마커를 구매하고 싶다면 어떤 대안이 있나요? 첫 번째의 경우, 원하는 마커의 브랜드 이름이나 색상을 지정하지 않았으므로 매장에 마커를 달라고 요청하고 단순히 요청에 한 금액만 요구합니다. 그래서 우리가 '그냥 마커가 필요해요'라고 말하면 그는 시장이나 그의 가게에서 가장 인기 있는 마커를 우리에게 건네주곤 했습니다. 기본 생성자는 말 그대로입니다! 두 번째 접근 방식은 매장에 가서 XYZ 브랜드의 빨간색 마커를 원한다고 지정하는 것입니다. 당신이 그 주제를 언급했으므로 그는 당신에게 그 표식을 줄 것입니다. 이 인스턴스에서는 매개변수가 이렇게 설정되었습니다. 그리고 매개변수화된 생성자는 말 그대로입니다! 세 번째 방법은 매장을 방문하여 이와 같은 모양의 마커(손에 있는 물리적 마커)를 원한다고 선언해야 합니다. 따라서 가게 주인은 그 표시를 알아차릴 것입니다. 당신이 괜찮다고 말하면 그는 당신에게 새로운 마커를 줄 것입니다. 따라서 해당 마커의 복사본을 만드십시오. 그리고 그것이 복사 생성자가 하는 일입니다!

생성자의 특징은 무엇입니까?

  1. 생성자는 자신이 속한 클래스와 동일한 이름을 갖습니다.
  2. 가능하더라도 생성자는 일반적으로 클래스의 공개 섹션에서 선언됩니다. 그러나 이것이 필수는 아닙니다.
  3. 생성자는 값을 반환하지 않기 때문에 반환 유형이 없습니다.
  4. 클래스 객체를 생성하면 생성자가 즉시 호출됩니다.
  5. 오버로드된 생성자가 가능합니다.
  6. 생성자를 가상으로 선언하는 것은 허용되지 않습니다.
  7. 생성자를 상속받을 수 없습니다.
  8. 생성자 주소는 참조할 수 없습니다.
  9. 메모리를 할당할 때 생성자는 new 및 delete 연산자를 암시적으로 호출합니다.

복사 생성자란 무엇입니까?

복사 생성자라고 알려진 멤버 함수는 동일한 클래스의 다른 객체를 사용하여 항목을 초기화합니다. 복사 생성자에 대한 심층적인 논의입니다.

클래스에 대해 하나 이상의 기본 생성자가 아닌 생성자(매개변수 포함)를 지정할 때마다 컴파일러가 이 상황에서 기본 생성자를 제공하지 않으므로 기본 생성자(매개변수 없음)도 포함해야 합니다. 가장 좋은 방법은 필수 생성자가 아니더라도 항상 기본 생성자를 선언하는 것입니다.

복사 생성자에는 동일한 클래스에 속하는 개체에 대한 참조가 필요합니다.

 Sample(Sample &amp;t) { id=t.id; } 

C++에서 소멸자는 무엇입니까?

생성자와 동등한 특수 멤버 함수는 소멸자입니다. 생성자는 클래스 객체를 생성하고 소멸자에 의해 소멸됩니다. '소멸자'라는 단어 뒤에 물결표() 기호가 오는 것은 클래스 이름과 동일합니다. 한 번에 하나의 소멸자만 정의할 수 있습니다. 생성자가 만든 객체를 파괴하는 한 가지 방법은 소멸자를 사용하는 것입니다. 결과적으로 소멸자는 오버로드될 수 없습니다. 소멸자는 어떤 인수도 받아들이지 않으며 아무것도 돌려주지 않습니다. 항목이 범위를 벗어나자마자 즉시 호출됩니다. 소멸자는 생성자가 생성한 개체에서 사용하는 메모리를 해제합니다. 소멸자는 사물을 파괴함으로써 사물을 창조하는 과정을 역전시킵니다.

클래스의 소멸자를 정의하는 데 사용되는 언어

 ~ () { } 

클래스 외부에서 클래스의 소멸자를 정의하는 데 사용되는 언어

 : : ~ (){}