上市
公开宣布的所有班级成员将向所有人开放。声明为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
在上面的程序中,数据成员的半径是公共的,因此我们可以在类外部访问它。
受保护的
受保护的访问修饰符与私有访问修饰符相似,不同之处在于,声明为“受保护”的类成员在该类外部不可访问,但可以由该类的任何子类(派生类)访问。
例子:
// 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++基础课程以及有关语言和STL的C++ STL课程。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。