c++11 에 추가된 기능

 

간단한 클래스나 구조체라면 굳이 생성자를 만들어 줄 필요 없이 예시처럼 간단히 초기화 할 수 있다.

클래스, 구조체 속에서 선언된 순서대로 {} 안에 값을 넣어주어 초기화 할 수 있다.

struct mystruct
{
	int myint;
	double mydouble;
	string mystring;
};

int main()
{
	cout << "그냥 생성" << endl;
	{
		mystruct st;
		cout << st.myint << " / " << st.mydouble << " / " << st.mystring << endl;
	} //출력값 : -858993460 / -9.25596e+61 /

	cout << "모든 변수 기본값 초기화 생성" << endl;
	{
		mystruct st{};
		cout << st.myint << " / " << st.mydouble << " / " << st.mystring << endl;
	} //출력값 : 0 / 0 /

	cout << "일부 변수 초기화, 나머지 기본 초기화 생성" << endl;
	{
		mystruct st{3};
		cout << st.myint << " / " << st.mydouble << " / " << st.mystring << endl;
	} //출력값 : 3 / 0 /

	cout << "모든 변수 초기화 생성" << endl;
	{
		mystruct st{3, 2.5, "yes!"};
		cout << st.myint << " / " << st.mydouble << " / " << st.mystring << endl;
	} //출력값 : 3 / 2.5 / yes!
}

 

 

구조체 속 클래스가 기본생성자가 금지되어있다면 어떻게 될까?

class Myclass
{
public:
	Myclass() = delete; //기본생성 금지됨
	Myclass(int num) : _num(num) {}
	int _num;
};

struct mystruct
{
	int myint;
	Myclass myclass;
	double mydouble;
	string mystring;
};
int main()
{
	mystruct st; // 컴파일 에러

	mystruct st{}; // 컴파일 에러

	mystruct st{ 1 }; // 컴파일 에러

	mystruct st{ 1,2 }; // ok
	cout << st.myint << " / " << st.myclass._num
		<< " / " << st.mydouble << " / " << st.mystring << endl;
	// 출력값 : 1 / 2 / 0 /
}

 

생성자 인자를 여러개 받는 클래스가 포함되어있다면?

class Myclass
{
public:
	Myclass() = delete;
	Myclass(int num1, int num2) : _num1(num1), _num2(num2) {}
	int _num1;
	int _num2;
};

struct mystruct
{
	int myint;
	Myclass myclass;
};

int main()
{
	mystruct st{ 1,{2,3} }; // ok
	cout << st.myint << " / " << st.myclass._num1 << ", " << st.myclass._num2 << endl;
    // 출력값 : 1 / 2, 3
}

 

그 외 stl에서의 활용

int main()
{
	list<int> lst{ 4,3,2,1 };
	for (int n : lst)
	{
		cout << n << ' ';
	}
	cout << endl;

	vector<int> vec{ 4,3,2,1 };
	for (int n : vec)
	{
		cout << n << ' ';
	}
	cout << endl;

	set<int> st{ 4,3,2,1 };
	for (int n : st)
	{
		cout << n << ' ';
	}
	cout << endl;
}

출력값 : 

4 3 2 1
4 3 2 1
1 2 3 4

 

 

'공부 > C\C++' 카테고리의 다른 글

jwt-cpp 사용하기 with.C/C++  (0) 2026.03.14
c++ friend  (0) 2025.07.24
c union  (0) 2025.07.05
c++ placement new  (0) 2025.07.04
c 매크로 - 함수형 매크로 ()  (0) 2025.06.28

+ Recent posts