여기에서는 C++의 균일 초기화에 대해 설명합니다. 이것은 C++11 버전에서 지원됩니다. 균일 초기화는 기본 유형에서 집계에 이르는 변수 및 개체를 초기화하기 위해 일관된 구문을 사용할 수 있도록 하는 기능입니다. 즉, 중괄호({})를 적용하여 초기화 값을 묶는 중괄호 초기화를 도입합니다.
구문
type var_name{argument_1, argument_2, .... argument_n} 동적으로 할당된 배열 초기화
예시(C++)
이해를 돕기 위해 다음 구현을 살펴보겠습니다. −
#include <bits/stdc++.h>
using namespace std;
int main() {
int* pointer = new int[5]{ 10, 20, 30, 40, 50 };
cout<lt;"The contents of array are: ";
for (int i = 0; i < 5; i++)
cout << pointer[i] << " " ;
} 출력
The contents of array are: 10 20 30 40 50
클래스의 배열 데이터 멤버 초기화
예시
#include <iostream>
using namespace std;
class MyClass {
int arr[3];
public:
MyClass(int p, int q, int r) : arr{ p, q, r } {};
void display(){
cout <<"The contents are: ";
for (int c = 0; c < 3; c++)
cout << *(arr + c) << ", ";
}
};
int main() {
MyClass ob(40, 50, 60);
ob.display();
} 출력
The contents are: 40, 50, 60,
반환할 개체를 암시적으로 초기화
예시
#include <iostream>
using namespace std;
class MyClass {
int p, q;
public:
MyClass(int i, int j) : p(i), q(j) {
}
void display() {
cout << "(" <<p <<", "<< q << ")";
}
};
MyClass func(int p, int q) {
return { p, q };
}
int main() {
MyClass ob = func(40, 50);
ob.display();
} 출력
(40, 50)
암시적으로 함수 매개변수 초기화
예시
#include <iostream>
using namespace std;
class MyClass {
int p, q;
public:
MyClass(int i, int j) : p(i), q(j) {
}
void display() {
cout << "(" <<p <<", "<< q << ")";
}
};
void func(MyClass p) {
p.display();
}
int main() {
func({ 40, 50 });
} 출력
(40, 50)