Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

Access modifiers ใน C++ คืออะไร?

Data hiding เป็นฟีเจอร์สำคัญของ Object Oriented Programming ที่ป้องกันไม่ให้ฟังก์ชันของโปรแกรมเข้าถึง internal representation ของ class type โดยตรง การจำกัดการเข้าถึง class members ระบุโดย labeled access modifiers: public, private, และ protected sections ภายใน class body

Default access สำหรับ members และ classes คือ private

class Base {
    public:
        // public members go here
    protected:
        // protected members go here
    private:
        // private members go here
};

Public member เข้าถึงได้จากทุกที่นอก class แต่ภายในโปรแกรม คุณสามารถ set และ get ค่าของ public variables โดยไม่ต้องใช้ member

Private member variable หรือ function ไม่สามารถเข้าถึง หรือแม้แต่มองเห็นจากนอก class ได้ เฉพาะ class และ friend functions เท่านั้นที่เข้าถึง private members ได้

Protected member variable หรือ function คล้าย private member แต่มีประโยชน์เพิ่มเติมคือเข้าถึงได้ใน child classes (derived classes)