什么是面向对象编程中的 'Access specifier'

What is 'Access specifier' in Object Oriented Programming

面向对象编程中的'Access specifier'是什么?

我已经多次搜索它的定义,但没有得到满意的答案。

任何人都可以用实际例子向我解释一下吗?....

提前致谢

它们是什么?

This wikipedia article 总结得差不多了。但是让我们详细说明几个要点。它开始说:

Access modifiers (or access specifiers) are keywords in object-oriented languages that set the accessibility of classes, methods, and other members. Access modifiers are a specific part of programming language syntax used to facilitate the encapsulation of components.1

因此,访问说明符 aka 访问修饰符采用某些 class、方法或变量,并决定允许其他哪些 class 使用它们。最常见的访问说明符是 PublicProtectedPrivate。这些含义可能因您使用的语言而异,但我将使用 C++ 作为示例,因为这就是本文所使用的内容。

Accessor Method |   Who Can Call It
-----------------------------------------------------------------------
Private         | Only the class who created it
Protected       | The class who created it and derived classes that "inherit" from this class
Public          | Everyone can call it

为什么这很重要?

OOP 编程的很大一部分是 Encapsulation。访问说明符允许封装。封装让您可以选择和选择哪些 class 可以访问程序的哪些部分,以及一个帮助您模块化程序和分离功能的工具。封装可以使调试更容易。如果变量返回意外值并且您知道该变量是私有的,那么您就会知道只有创建它的 class 会影响这些值,因此问题是内部的。此外,它还可以防止其他程序员意外更改可能无意中破坏整个 class 的变量。

简单示例

查看我们看到的文章中的示例代码 Struct B 为了清楚起见,我在其中添加了 public

struct B { // default access modifier inside struct is public
  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;
};

如果您创建了一个继承结构 C 并尝试使用来自结构 B

的成员,将会发生这种情况
//struct C is going to inherit from struct B
struct C :: B { 
      public:
        void set_m(int v) {m = v}  // m is protected, but since C inherits from B
                                   // it is allowed to access m.
        void set_x(int v) (x = v)  // Error X is a private member of B and 
                                   // therefore C can't change it.
    };

如果我的主程序 where to try 访问 这些成员,就会发生这种情况。

    int main(){
  //Create Struct
  B structB;
  C structC;

  structB.set_n(0); // Good Since set_n is public
  structB.f(); // Good Since f() is public

  structB.m = 0; // Error because m is a protected member of Struct B 
                 // and the main program does not "inherit" from struct B"

  structB.x = 0; // Error because x is a private member of Struct B

  structC.set_n() // Inheritied public function from C, Still Good
  structC.set_m() // Still Good

  structC.m = 0   // Error Main class can't access m because it's protected.
  structC.x = 0;  // Error still private.

  return 0;
}

我可以添加另一个使用继承的示例。如果您需要更多解释,请告诉我。