1, the difference between public and private
In C + +, to control the access and encapsulation (hiding) of members of a class, the public and private specifiers are used to encapsulate the members of the class.
A member that is defined after the public specifier can be accessed throughout the program, and the public member defines the interface of the class
A member defined after the private specifier can be accessed by a member function of the class, but cannot be accessed using the class's code, and the private part encapsulates (hides) the implementation details of the class.
For example:
struct sales_data{
Public
Sales_data () = default; Take the default constructor
Sales_data (const string &s, unsigned int n,double p):
Bookno (s), Units_sold (n), Revenue (P*n) {}
Constructor Initial Value List
Std:string ISBN () const{return bookno;}
Private
Std:string Bookno;
ungsined units_sold = 0;
Double revenue = 0.0;
};
In the class above, the constructors and some member functions immediately following public can be accessed throughout the program. And the private behind is not accessible by the entire program.
Note: A class can contain 0 or more access specifiers, and there is no strict qualification for how many times an access descriptor can occur. Each access specifier specifies the next member access level, which is valid until the next access specifier is present, or until the end of the class is reached.
2. About the difference between class and struct keywords
In the definition of the class above, we are using the struct keyword, in fact it is perfectly possible to replace the struct with class.
In C + +, the struct and class keywords define a class that is possible, with the only difference being that the default access rights to struct and class are not the same .
class You can define a member before its first access specifier , which depends on how the class is defined, that is, using the struct or by using class to define a class.
If the struct keyword, the member defined before the descriptor is public
If the class keyword is defined, the member before the descriptor is private
For example:
struct sales_data{
Sales_data () = default; Take the default constructor
Sales_data (const string &s, unsigned int n,double p):
Bookno (s), Units_sold (n), Revenue (P*n) {}
Constructor Initial Value List
Std:string ISBN () const{return bookno;}
Std:string Bookno;
ungsined units_sold = 0;
Double revenue = 0.0;
};//All members of the class here are public members
class sales_data{
Sales_data () = default; Take the default constructor
Sales_data (const string &s, unsigned int n,double p):
Bookno (s), Units_sold (n), Revenue (P*n) {}
Constructor Initial Value List
Std:string ISBN () const{return bookno;}
Std:string Bookno;
ungsined units_sold = 0;
Double revenue = 0.0;
};//All members of the class here are class members
C + + study notes (14): Public, private, struct, class