Post

(C++) 구조체와 클래스의 차이 ( struct / class )

구조체와 클래스의 차이 : 기본 접근 지정자 말고는 없음.

class는 기본적으로 private struct는 기본적으로 public

생성한 객체의 위치는, 클래스냐 구조체냐가 결정하는게 아니라, new로 만들었느냐 그냥 선언했느냐가 결정.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <stdio.h>
struct ST {
int a;
};
class CL {
public:
int a;
};
int main(void) {
struct ST s;
s.a = 1;
CL c;
c.a = 1;
printf("struct : %p\n", &s.a);
printf("class  : %p\n", &c.a);
return 0;
}

1
2
3
4
struct : 0x7ffee9e09a50
class  : 0x7ffee9e09a54

보다시피 둘 다 지역변수로 스택에 잡힌다. new를 사용하면?

1
2
3
4
5
6
7
8
9
10
11
12
int main(void) {
struct ST\* s = new ST();
s->a = 1;
CL\* c = new CL();
c->a = 1;
printf("struct : %p\n", &s->a);
printf("class  : %p\n", &c->a);
delete s;
delete c;
return 0;
}

1
2
3
4
struct : 0x5600f5770e70
class  : 0x5600f5770e90

둘 다 힙에 잡힌다.

struct alignment 설정하기 : struct나 class나 둘 다 된다.

1
2
3
4
\_\_attribute\_\_ ((aligned(1), packed))    // until GCC 4.0
#pragma pack(push, 1)       // since GCC 4.0 / MS Visual C
#pragma pack(pop)

따라서 아래를 사용하는 편이 좋다.

멤버 함수를 정의하는 경우 크기에 영항을 미치는가? X

sizeof해보면 알 수 있다. 멤버 함수는 객체의 크기에 영향을 미치지 않는다. 단, virtual로 선언된 멤버 함수가 있는 경우는 예외. 마찬가지로 static 변수를 선언하는 것도 크기에 영향을 미치지 않는다. * static 변수 초기화는 전역 스코프에서 해야한다는 것 유의.

[C/C++] 비트 필드 구조체

https://dojang.io/mod/page/view.php?id=473

https://docs.microsoft.com/ko-kr/cpp/cpp/cpp-bit-fields?view=vs-2017

구조체 선언과 동시에 초기화

참고 )https://dojang.io/mod/page/view.php?id=408,https://dojang.io/mod/page/view.php?id=446

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
PresentFlag enum

  

struct \_radiotap\_field\_info {
uint8\_t align;
uint8\_t size;
}

  

static const struct \_radiotap\_field\_info rtap\_namespace\_sizes[] = {
[PresentFlag::TSFT]              = { .align = 8, .size = 8, },
[PresentFlag::FLAGS]             = { .align = 1, .size = 1, },
[PresentFlag::RATE]              = { .align = 1, .size = 1, },
[PresentFlag::CHANNEL]           = { .align = 2, .size = 4, },
[PresentFlag::FHSS]              = { .align = 2, .size = 2, },
[PresentFlag::DBM\_ANTSIGNAL]     = { .align = 1, .size = 1, },
[PresentFlag::DBM\_ANTNOISE]      = { .align = 1, .size = 1, },
[PresentFlag::LOCK\_QUALITY]      = { .align = 2, .size = 2, },
[PresentFlag::EXAMPLE]           = { .size = 2, .align = 2, },   // 구조체 순서랑 안맞으면 에러.
// Error sorry, unimplemented: non-trivial designated initializers not supported
// 중간에 숫자 빠진거 있어도 같은 에러. 0부터 n까지 다 채워야 함.
};

This post is licensed under CC BY 4.0 by the author.