Trong C++, struct và class về cơ bản giống nhau. Nhưng có vài khác biệt nhỏ:
- Thành viên
classmặc địnhprivate,structmặc địnhpublic.
Ví dụ 1: Class (private mặc định)
#include <iostream>
using namespace std;
class my_class {
int x = 10;
};
int main() {
my_class my_ob;
cout << my_ob.x; // Lỗi: x là private
return 0;
}
Kết quả
Lỗi compile: thành viên private không truy cập được.
Ví dụ 2: Struct (public mặc định)
#include <iostream>
using namespace std;
struct my_struct {
int x = 10;
};
int main() {
my_struct my_ob;
cout << my_ob.x; // OK: x là public
return 0;
}
Kết quả
10
- Kế thừa: struct kế thừa từ class/struct, mặc định
public; class kế thừa, mặc địnhprivate.
Ví dụ 3: Class kế thừa class (private mặc định)
#include <iostream>
using namespace std;
class my_base_class {
public:
int x = 10;
};
class my_derived_class : my_base_class { }; // private inheritance
int main() {
my_derived_class d;
cout << d.x; // Lỗi: x không truy cập được
return 0;
}
Kết quả
Lỗi compile: x của base class không truy cập được.
Ví dụ 4: Struct kế thừa class (public mặc định)
#include <iostream>
using namespace std;
class my_base_class {
public:
int x = 10;
};
struct my_derived_struct : my_base_class { }; // public inheritance
int main() {
my_derived_struct d;
cout << d.x; // OK
return 0;
}
Kết quả
10