아카이빙/C, C++

struct와 class 차이

셩님 2018. 5. 27. 03:17

struct와 class 차이

  • c++에서 struct와 class는 무슨 차이가 있을까?

  • class는 객체지향적으로, 멤버 변수에 대한 접근 권한을 설정할 수 있고, 생성자, 메소드를 추가할 수 있고, 상속도 되지만 struct는 안된다!

  • 그런 줄 알았는데 아니었다. struct에서도 다 된다. (C++)


struct

#include <cstdio>
#include <iostream>

using namespace std;

struct Sample {
private:
int val;
public:
Sample() {
val = 9;
}

void Print() {
cout << val << endl;
}
};

struct Child : Sample {
//empty
};


int main() {

Sample s;
Child c;

s.Print();
c.Print();

return 0;
}
  • 놀랍군...

  • 그렇다면 무슨 차이가 있지?


struct와 class의 차이

  • 상속 형태의 default

    • struct 는 public

    • class 는 private

  • 멤버 변수나 함수의 default 접근 권한

    • struct = public

    • class = private


'아카이빙 > C, C++' 카테고리의 다른 글

상속에서 객체의 생성, 소멸과정  (0) 2018.05.27
malloc과 new의 차이  (0) 2018.05.27
strcpy와 strncpy  (0) 2018.05.27
string과 character 배열  (0) 2018.05.26
malloc, calloc, realloc, free  (0) 2018.05.26