프로그래밍 언어/C++
struct를 초기화 하는 3가지 방법
Sondho
2022. 2. 17. 16:42
1.
#include <iostream>
int main()
{
struct MyStruct
{
int x;
int y;
};
MyStruct not_init_pos; // 초기화 하지 않음
std::cout << "not init_pos x: " << not_init_pos.x << std::endl;
std::cout << "not init_pos y: " << not_init_pos.y << std::endl;
MyStruct init_pos = {}; // 모든 멤버를 0으로 초기화
std::cout << "init pos x: " << init_pos.x << std::endl;
std::cout << "init pos y: " << init_pos.y << std::endl;
return 0;
}
실행 결과
2.
#include <iostream>
int main()
{
struct MyStruct
{
int x;
int y;
MyStruct():x(0), y(0) {};
};
MyStruct pos;
std::cout << "pos x: " << pos.x << std::endl;
std::cout << "pos y: " << pos.y << std::endl;
return 0;
}
실행 결과
3.
#include <iostream>
int main()
{
struct MyStruct
{
int x;
int y;
MyStruct()
{
memset(this, 0x0, sizeof(struct MyStruct));
}
};
MyStruct pos;
std::cout << "pos x: " << pos.x << std::endl;
std::cout << "pos y: " << pos.y << std::endl;
return 0;
}
실행 결과
참고
https://stackoverflow.com/questions/1069621/are-members-of-a-c-struct-initialized-to-0-by-default
Are members of a C++ struct initialized to 0 by default?
I have this struct: struct Snapshot { double x; int y; }; I want x and y to be 0. Will they be 0 by default or do I have to do: Snapshot s = {0,0}; What are the other ways to zero out ...
stackoverflow.com