📜  C++ 中的公共 vs 受保护示例

📅  最后修改于: 2021-09-15 01:09:24             🧑  作者: Mango

上市

所有公开声明的班级成员都将向所有人开放。其他类也可以访问声明为 public 的数据成员和成员函数。可以从程序中的任何地方使用直接成员访问运算符(.) 对该类的对象访问该类的公共成员。

例子:

// C++ program to demonstrate public
// access modifier
  
#include 
using namespace std;
  
// class definition
class Circle {
public:
    double radius;
  
    double compute_area()
    {
        return 3.14 * radius * radius;
    }
};
  
// main function
int main()
{
    Circle obj;
  
    // accessing public data member outside class
    obj.radius = 5.5;
  
    cout << "Radius is: " << obj.radius << "\n";
    cout << "Area is: " << obj.compute_area();
    return 0;
}
输出:
Radius is: 5.5
Area is: 94.985

在上面的程序中,数据成员radius是公共的,所以我们可以在类外访问它。

受保护

Protected 访问修饰符与 private 访问修饰符类似,区别在于声明为 Protected 的类成员在类之外是不可访问的,但可以被该类的任何子类(派生类)访问。
例子:

// C++ program to demonstrate
// protected access modifier
#include 
using namespace std;
  
// base class
class Parent {
    // protected data members
protected:
    int id_protected;
};
  
// sub class or derived class
class Child : public Parent {
  
public:
    void setId(int id)
    {
  
        // Child class is able to access the inherited
        // protected data members of base class
  
        id_protected = id;
    }
  
    void displayId()
    {
        cout << "id_protected is: " << id_protected << endl;
    }
};
  
// main function
int main()
{
  
    Child obj1;
  
    // member function of the derived class can
    // access the protected data members of the base class
  
    obj1.setId(81);
    obj1.displayId();
    return 0;
}

公共和受保护之间的区别

Public Protected
All the class members declared under public will be available to everyone. Protected access modifier is similar to that of private access modifiers.
The data members and member functions declared public can be accessed by other classes too. The class member declared as Protected are inaccessible outside the class but they can be accessed by any subclass(derived class) of that class.
想要从精选的视频和练习题中学习,请查看C++ 基础课程,从基础到高级 C++ 和C++ STL 课程,了解语言和 STL。要完成从学习语言到 DS Algo 等的准备工作,请参阅完整的面试准备课程