ShovelingLife
A Game Programmer
ShovelingLife
전체 방문자
오늘
어제
  • 분류 전체보기 (1080) N
    • 그래픽스 (57)
      • 공통 (19)
      • 수학 물리 (22)
      • OpenGL & Vulkan (1)
      • DirectX (14)
    • 게임엔진 (184)
      • Unreal (69)
      • Unity (104)
      • Cocos2D-X (3)
      • 개인 플젝 (8)
    • 코딩테스트 (221)
      • 공통 (7)
      • 프로그래머스 (22)
      • 백준 (162)
      • LeetCode (19)
      • HackerRank (2)
      • 코딩테스트 알고리즘 (8)
    • CS (238) N
      • 공통 (21)
      • 네트워크 (44)
      • OS & 하드웨어 (58) N
      • 자료구조 & 알고리즘 (98)
      • 디자인패턴 (6)
      • UML (4)
      • 데이터베이스 (7)
    • 프로그래밍 언어 (351) N
      • C++ (168)
      • C# (90)
      • Java (9)
      • Python (35) N
      • SQL (30)
      • JavaScript (8)
      • React (7)
    • 그 외 (20)
      • Math (5)
      • 일상 (5)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

  • Source Code 좌측 상단에 복사 버튼 추가 완료
  • 언리얼 엔진 C++ 빌드시간 단축 꿀팁
  • 게임 업계 코딩테스트 관련
  • 1인칭 시점으로 써내려가는 글들

인기 글

태그

  • 티스토리챌린지
  • 백준
  • c#
  • Unity
  • 포인터
  • C++
  • 유니티
  • python
  • 배열
  • C
  • 그래픽스
  • 함수
  • 언리얼
  • string
  • 파이썬
  • 알고리즘
  • 오블완
  • SQL
  • 클래스
  • 문자열

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
ShovelingLife

A Game Programmer

프로그래밍 언어/C++

C++ 중괄호 초기화

2022. 8. 19. 13:35

특히 비교적 간단한 생성자에 대한 class생성자를 항상 정의할 필요는 없다. 사용자는 다음 예제와 같이 균일한 class 초기화를 사용하여 개체를 초기화하거나 struct 초기화할 수 있다.

// no_constructor.cpp
// Compile with: cl /EHsc no_constructor.cpp
#include <time.h>

// No constructor
struct TempData
{
    int StationId;
    time_t timeSet;
    double current;
    double maxTemp;
    double minTemp;
};

// Has a constructor
struct TempData2
{
    TempData2(double minimum, double maximum, double cur, int id, time_t t) :
       stationId{id}, timeSet{t}, current{cur}, maxTemp{maximum}, minTemp{minimum} {}
    int stationId;
    time_t timeSet;
    double current;
    double maxTemp;
    double minTemp;
};

int main()
{
    time_t time_to_set;

    // Member initialization (in order of declaration):
    TempData td{ 45978, time(&time_to_set), 28.9, 37.0, 16.7 };

    // Default initialization = {0,0,0,0,0}
    TempData td_default{};

    // Uninitialized = if used, emits warning C4700 uninitialized local variable
    TempData td_noInit;

    // Member declaration (in order of ctor parameters)
    TempData2 td2{ 16.7, 37.0, 28.9, 45978, time(&time_to_set) };

    return 0;
}

생성자가 있거나 classstruct 없는 경우 멤버가 에 선언되는 class 순서대로 목록 요소를 제공한다. class 생성자가 있는 경우 매개 변수 순서대로 요소를 제공한다. 형식에 암시적으로 또는 명시적으로 선언된 기본 생성자가 있는 경우 기본 중괄호 초기화(빈 중괄호 포함)를 사용할 수 있다. 예를 들어 기본 및 기본 중괄호가 아닌 초기화를 모두 사용하여 다음 class 을 초기화할 수 있다.

#include <string>
using namespace std;

class class_a {
public:
    class_a() {}
    class_a(string str) : m_string{ str } {}
    class_a(string str, double dbl) : m_string{ str }, m_double{ dbl } {}
double m_double;
string m_string;
};

int main()
{
    class_a c1{};
    class_a c1_1;

    class_a c2{ "ww" };
    class_a c2_1("xx");

    // order of parameters is the same as the constructor
    class_a c3{ "yy", 4.4 };
    class_a c3_1("zz", 5.5);
}

클래스에 기본이 아닌 생성자가 있는 경우 클래스 멤버가 중괄호 이니셜라이저에 표시되는 순서는 이전 예제와 같이 class_a 멤버가 선언되는 순서가 아니라 해당 매개 변수가 생성자에 표시되는 순서이다. 그렇지 않으면 형식에 선언된 생성자가 없는 경우 멤버 이니셜라이저는 선언된 것과 동일한 순서로 중괄호 이니셜라이저에 표시되어야 한다. 이 경우 원하는 만큼 공용 멤버를 초기화할 수 있지만 멤버를 건너뛸 수는 없다. 다음 예제에서는 선언된 생성자가 없을 때 중괄호 초기화에 사용되는 순서를 보여준다.

class class_d {
public:
    float m_float;
    string m_string;
    wchar_t m_char;
};

int main()
{
    class_d d1{};
    class_d d1{ 4.5 };
    class_d d2{ 4.5, "string" };
    class_d d3{ 4.5, "string", 'c' };

    class_d d4{ "string", 'c' }; // compiler error
    class_d d5{ "string", 'c', 2.0 }; // compiler error
}

기본 생성자가 명시적으로 선언되었지만 삭제된 것으로 표시된 경우 기본 중괄호 초기화를 사용할 수 없다.

class class_f {
public:
    class_f() = delete;
    class_f(string x): m_string { x } {}
    string m_string;
};
int main()
{
    class_f cf{ "hello" };
    class_f cf1{}; // compiler error C2280: attempting to reference a deleted function
}

일반적으로 초기화를 수행하는 모든 위치(예: 함수 매개 변수 또는 반환 값 new 또는 키워드 포함)에서 중괄호 초기화를 사용할 수 있다.

class_d* cf = new class_d{4.5};
kr->add_d({ 4.5 });
return { 4.5 };

출처 : https://docs.microsoft.com/ko-kr/cpp/cpp/initializing-classes-and-structs-without-constructors-cpp?view=msvc-170

저작자표시 (새창열림)

'프로그래밍 언어 > C++' 카테고리의 다른 글

C++ 포인터 객체 자살 (delete this)  (0) 2022.08.24
C++ 정적 바인딩과 동적 바인딩의 차이점  (0) 2022.08.21
C++ 비동기 (Asynchronous) 실행  (0) 2022.08.17
C++ 동기(synchronous)와 비동기(asynchronous) / 블로킹(blocking)과 논블로킹(non-blocking)  (0) 2022.08.16
C++ Copy and Swap idiom  (0) 2022.08.08
    '프로그래밍 언어/C++' 카테고리의 다른 글
    • C++ 포인터 객체 자살 (delete this)
    • C++ 정적 바인딩과 동적 바인딩의 차이점
    • C++ 비동기 (Asynchronous) 실행
    • C++ 동기(synchronous)와 비동기(asynchronous) / 블로킹(blocking)과 논블로킹(non-blocking)
    ShovelingLife
    ShovelingLife
    Main skill stack => Unity C# / Unreal C++ Studying Front / BackEnd, Java Python

    티스토리툴바