C++에서 구조와 클래스는 기본적으로 동일합니다. 그러나 약간의 차이가 있습니다. 이러한 차이점은 아래와 같습니다.
클래스 멤버는 기본적으로 private이지만 구조체의 멤버는 public입니다. 차이점을 알아보기 위해 이 두 코드를 살펴보겠습니다.
예제 코드
#include <iostream>
using namespace std;
class my_class {
int x = 10;
};
int main() {
my_class my_ob;
cout << my_ob.x;
} 출력
This program will not be compiled. It will generate compile time error for the private data member.
예시 코드
#include <iostream>
using namespace std;
struct my_struct{
int x = 10;
};
int main() {
my_struct my_ob;
cout << my_ob.x;
} 출력
10
클래스나 구조체에서 구조체를 파생할 때 해당 기본 클래스의 기본 액세스 지정자는 public이지만 클래스를 파생할 때 기본 액세스 지정자는 private입니다.
예시 코드
#include <iostream>
using namespace std;
class my_base_class {
public:
int x = 10;
};
class my_derived_class : my_base_class{
};
int main() {
my_derived_class d;
cout << d.x;
} 출력
This program will not be compiled. It will generate compile time error that the variable x of the base class is inaccessible
예시 코드
#include <iostream>
using namespace std;
class my_base_class {
public:
int x = 10;
};
struct my_derived_struct : my_base_class{
};
int main() {
my_derived_struct d;
cout << d.x;
} 출력
10