📌  相关文章
📜  C++ 中 Public 和 Private 的区别示例

📅  最后修改于: 2021-09-13 02:30:13             🧑  作者: 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是公共的,所以我们可以在类外访问它。

私人的

声明为私有的类成员只能由类内部的函数访问。它们不允许被类外的任何对象或函数直接访问。只有成员函数或友元函数才能访问类的私有数据成员。
例子:

// 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

公共和私人之间的区别

Public Private
All the class members declared under public will be available to everyone. The class members declared as private can be accessed only by the functions inside the class.
The data members and member functions declared public can be accessed by other classes too. Only the member functions or the friend functions are allowed to access the private data members of a class.
The public members of a class can be accessed from anywhere in the program using the direct member access operator (.) with the object of that class. They are not allowed to be accessed directly by any object or function outside the class.
想要从精选的视频和练习题中学习,请查看C++ 基础课程,从基础到高级 C++ 和C++ STL 课程,了解语言和 STL。要完成从学习语言到 DS Algo 等的准备工作,请参阅完整的面试准备课程