Chỉ định truy cập

Bách khoa toàn thư mở Wikipedia

Chỉ định truy cập (tiếng Anh: access modifier hay access specifiers) là từ khóa trong lập trình hướng đối tượng để thiết lập khả năng truy cập của lớp, phương thức, và các thành viên khác. Chỉ định truy cập là một phần cụ thể của cú pháp ngôn ngữ lập trình được dùng để tạo điều kiện để đóng gói các thành phần.[1]

Tên từ khóa[sửa | sửa mã nguồn]

C++ có 3 chỉ định là public, protected, và private. C# có các chỉ định public, protected ,internal, private, và protected internal. Javapublic, package, protected, và private.

Ví dụ trong C++[sửa | sửa mã nguồn]

#include <iostream>
using std::cout;
using std::endl;

struct B { // default access modifier inside struct is public
    void set_n(int v) { n = v; }
    void f()          { cout << "B::f" << endl; }
  protected:
    int m, n; // B::m, B::n are protected
  private:
    int x;
};
 
struct D: B {
    using B::m;               // D::m is public
    int get_n() { return n; } // B::n is accessible here, but not outside
//  int get_x() { return x; } // ERROR, B::x is inaccessible here
 private:
    using B::f;               // D::f is private
};
 
int main() {
    D d;

//  d.x = 2; // ERROR, private
//  d.n = 2; // ERROR, protected
    d.m = 2; // protected B::m is accessible as D::m

    d.set_n(2); // calls B::set_n(int)
    cout << d.get_n() << endl; // output: 2

//  d.f();   // ERROR, B::f is inaccessible as D::f

    B& b = d; // b references d and "views" it as being type B

//  b.x = 3; // ERROR, private
//  b.n = 3; // ERROR, protected
//  b.m = 3; // ERROR, B::m is protected

    b.set_n(3); // calls B::set_n(int)
//  cout << b.get_n(); // ERROR, 'struct B' has no member named 'get_n'

    b.f();   // calls B::f()
    return 0;
}

Tham khảo[sửa | sửa mã nguồn]

Ghi chú[sửa | sửa mã nguồn]

  1. ^ Mayo 2002, tr. 199.

Tham khảo[sửa | sửa mã nguồn]

  • Mayo, Joseph (2002), C Sharp Unleashed, Sams publishing, ISBN 9780672321221