受保护的
受保护的访问修饰符与私有访问修饰符相似,不同之处在于,声明为“受保护”的类成员在该类外部无法访问,但可以由该类的任何子类(派生类)访问。
例子:
// 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 the 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;
}
输出:
id_protected is: 81
私人的
声明为私有的类成员只能由该类内部的函数访问。类之外的任何对象或函数都不允许直接访问它们。只允许成员函数或朋友函数访问类的私有数据成员。
例子:
// C++ program to demonstrate private
// access modifier
#include
using namespace std;
class Circle {
// private data member
private:
double radius;
// public member function
public:
void compute_area(double r)
{
// member function can access private
// data member radius
radius = r;
double area = 3.14 * radius * radius;
cout << "Radius is: " << radius << endl;
cout << "Area is: " << area;
}
};
// main function
int main()
{
// creating object of the class
Circle obj;
// trying to access private data member
// directly outside the class
obj.compute_area(1.5);
return 0;
}
输出:
Radius is: 1.5
Area is: 7.065
私有与受保护之间的区别
Private | Protected |
---|---|
The class members declared as private can be accessed only by the functions inside the class. | Protected access modifier is similar to that of private access modifiers. |
Only the member functions or the friend functions are allowed to access the private data members of a class. | 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等的更多准备工作,请参阅“完整面试准备课程” 。