산업 제조
산업용 사물 인터넷 | 산업자재 | 장비 유지 보수 및 수리 | 산업 프로그래밍 |
home  MfgRobots >> 산업 제조 >  >> Industrial programming >> C 언어

C++ 생성자 초기화 목록:사용 이유 및 방법

객체를 인스턴스화할 때 생성자는 종종 멤버 변수의 초기화를 처리합니다. 이러한 멤버의 경우 생성자의 초기화 목록은 생성자의 본문이 실행되기 전에 간단하고 효율적인 초기화 방법을 제공합니다. 성능 외에도 때로는 const 변수나 기본 클래스의 멤버 때문에 필수이기도 합니다.

생성자 초기화 목록이란 무엇입니까?

생성자 초기화 목록은 멤버 변수를 직접 초기화하는 절차이므로 복사해서 할당하는 기본 생성자가 없습니다.

구문

생성자 목록 초기화 구문은 다음과 같습니다.

ClassName(type1 param1, type2 param2) : member1(param1), member2(param2) {
 // Constructor body
 
}

여기서 member1과 member2는 생성자 본문이 실행되기 전에 param1과 param2로 초기화됩니다.

생성자 초기화 목록 예시

초기화 목록을 사용하는 방법을 보여주는 간단한 예는 다음과 같습니다.

#include <iostream>
#include <string>
class Student {
public:
 Student(const std::string& name, int age) : name(name), age(age) {}
 void display() const {
 std::cout << "Name: " << name << ", Age: " << age << "\n";
 }
 private:
 std::string name;
 int age;
};
int main() {
 Student s("Navya", 20);
 s.display();
 return 0;
}

출력

Name: Navya, Age: 20

생성자 초기화 목록을 사용하는 이유

특별한 경우

다음에서는 생성자 초기화 목록에 대한 몇 가지 특별한 경우에 대해 설명합니다.

Const 또는 Reference 회원

Const 변수와 참조 멤버는 재할당이 불가능하므로 초기화 목록에서 초기화해야 합니다.

class Config {
public:
 Config(const std::string& product, const int & model) 
 : product (product), model(model) {}
 private:
 const std::string product;
 const int & model; 
};

기본 클래스 초기화

파생 클래스가 기본 클래스에서 상속되면 초기화 목록을 사용하여 기본 클래스 생성자를 호출할 수 있습니다.

class Base {
 public:
 Base(int value) : baseValue(value) {}
 protected:
 int baseValue;
};
class Derived : public Base {
 public:
 Derived(int value, int extra) : Base(value), extraValue(extra) {}
 private:
 int extraValue;
};

C 언어

  1. C - 헤더 파일
  2. C#의 마스터 중첩 루프:For, While 및 Do-While 설명
  3. C 중단 및 계속
  4. C에서 상수 포인터 및 상수에 대한 포인터 익히기
  5. C# 연산자 우선 순위 및 연관성
  6. C++ 개요
  7. C - 범위 규칙
  8. 예제가 있는 C 라이브러리의 malloc() 함수
  9. C++ 전처리기
  10. C# - 제네릭