ใน C++ โครงสร้างและคลาสนั้นเหมือนกัน แต่มีความแตกต่างเล็กน้อยบางประการ ความแตกต่างเหล่านี้มีดังนี้
สมาชิกของคลาสเป็นแบบส่วนตัวโดยค่าเริ่มต้น แต่สมาชิกของโครงสร้างเป็นแบบสาธารณะ ให้เราดูรหัสทั้งสองนี้เพื่อดูความแตกต่าง
โค้ดตัวอย่าง
#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
เมื่อเราได้รับโครงสร้างจากคลาสหรือโครงสร้าง ตัวระบุการเข้าถึงเริ่มต้นของคลาสพื้นฐานนั้นเป็นแบบสาธารณะ แต่เมื่อเราได้รับคลาส ตัวระบุการเข้าถึงเริ่มต้นจะเป็นแบบส่วนตัว
โค้ดตัวอย่าง
#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