ในโพสต์นี้ เราจะเข้าใจความแตกต่างระหว่างตัวแก้ไขการเข้าถึงแบบส่วนตัวและแบบมีการป้องกันใน C++
ตัวแก้ไขการเข้าถึงส่วนตัว
-
ประกาศโดยใช้คีย์เวิร์ด "ส่วนตัว" ตามด้วย ":"
-
ไม่สามารถเข้าถึงได้นอกชั้นเรียน
-
คีย์เวิร์ด "ส่วนตัว" คือตัวแก้ไขการเข้าใช้ที่ทำให้แน่ใจว่าฟังก์ชันและคุณลักษณะภายในคลาสจะเข้าถึงได้โดยสมาชิกของคลาสที่ได้รับการประกาศเท่านั้น
-
เฉพาะฟังก์ชันของสมาชิกหรือฟังก์ชันของเพื่อนเท่านั้นที่ได้รับอนุญาตให้เข้าถึงข้อมูลที่ระบุว่าเป็น "ส่วนตัว"
ตัวอย่าง
#include <iostream>
using namespace std;
class base_class{
private:
string my_name;
int my_age;
public:
void getName(){
cout << "Enter the name... ";
cin >> my_name;
cout << "Enter the age... ";
cin >> my_age;
}
void printIt(){
cout << "The name is : " << my_name << endl;
cout << "The age is: " << my_age << endl;
}
};
int main(){
cout<<"An object of class is created"<< endl;
base_class my_instance;
my_instance.getName();
my_instance.printIt();
return 0;
} ผลลัพธ์
/tmp/u5NtWSnX5A.o An object of class is created Enter the name... Jane Enter the age... 34 The name is : Jane The age is: 34
ตัวแก้ไขการเข้าถึงที่มีการป้องกัน
-
ตัวแก้ไขการเข้าถึงที่มีการป้องกันนั้นคล้ายกับตัวแก้ไขการเข้าถึงส่วนตัว
-
ประกาศโดยใช้คีย์เวิร์ด 'protected' ตามด้วย ':'
-
สมาชิกชั้นเรียนที่ได้รับการประกาศว่า "ได้รับการคุ้มครอง" จะเข้าถึงภายนอกชั้นเรียนไม่ได้
-
สามารถเข้าถึงได้ภายในชั้นเรียนที่มีการประกาศ
-
นอกจากนี้ยังสามารถเข้าถึงได้โดยคลาสที่ได้รับซึ่งคลาสพาเรนต์ประกอบด้วยสมาชิก 'ที่ได้รับการป้องกัน'
-
ใช้ในขณะที่ทำงานกับแนวคิดการสืบทอด
ตัวอย่าง
#include <iostream>
using namespace std;
class base_class{
private:
string my_name;
int my_age;
protected:
int my_salary;
public:
void getName(){
cout << "Enter the name... ";
cin >> my_name;
cout << "Enter the age... ";
cin >> my_age;
}
void printIt(){
cout << "The name is : " << my_name << endl;
cout << "The age is: " << my_age << endl;
}
};
class derived_class : public base_class{
private:
string my_city;
public:
void set_salary(int val){
my_salary = val;
}
void get_data_1(){
getName();
cout << "Enter the city... ";
cin >> my_city;
}
void print_it_1(){
cout << "The salary is: " << my_salary << endl;
printIt();
cout << "The city is: " << my_city << endl;
}
};
int main(){
cout<<"Instance of derived class is being created.."<<endl;
derived_class my_instance_2 ;
my_instance_2.set_salary(100);
my_instance_2.get_data_1();
my_instance_2.print_it_1();
return 0;
} ผลลัพธ์
/tmp/u5NtWSnX5A.o Instance of derived class is being created.. Enter the name... Jane Enter the age... 23 Enter the city... NewYork The salary is: 100 The name is : Jane The age is: 23 The city is: NewYork