📜  示例中C ++中的Public和Private之间的区别

📅  最后修改于: 2021-05-31 18:07:55             🧑  作者: 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

在上面的程序中,数据成员的半径是公共的,因此我们可以在类外部访问它。

私人的

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

// 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++基础课程以及有关语言和STL的C++ STL课程。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”