Hello, how does the C + + (35) class hide the money? 6.2.4 Copy Constructors

Source: Internet
Author: User

Access control for 6.2.6 class members

Class members include member variables and member functions of the class, which are used to describe the properties and behavior of the class, respectively. The access control of a class member determines which members are public, can be accessed by outsiders, can be accessed by themselves, and which members are private and accessible only within the class. Just like a person's purse, only he can move, others are not moving. And like the hidden money of his own only know, for other people, the money is completely hidden.

You might ask, why is it not good to have access to a class member and to be impartial and accessible to anyone? This is because in the real world, people's access to things is controlled, we can access something, but it is impossible to access anything. It's like we can only know how much money we have in our wallets, and we don't know how much money they have in their wallets. This is reflected in C + + and becomes the access control for class members. It can be imagined that the money in the purse can only be accessed by itself and the other person is not authorized to access it. When it becomes a property of the class "human", after being represented by a member variable, the access nature should also be controlled, accessible only by the behavior of the class itself (member function), which is invisible to other external functions, and cannot be accessed naturally. If access is not controlled and anyone can access it, it is likely that other functions (thieves) will incorrectly modify the data that should not be modified, and data security cannot be guaranteed. In other words, in order for the money in our wallets to peacefully, we have to control the access of class members to avoid unsafe access for members of the class.

In C + +, access control for a class member is achieved by setting the access level of the member. Depending on the size of the access scope, the access level is divided into public type (common), Protection type (protected), and private type three, as shown in 6-9.

1. Public type

Members of a public type are decorated with the key, which is a member of a public type, with a member variable or a member function preceded by a common keyword. Access to members of public types is unrestricted, accessible both inside and outside the class, but more as an interface to the outside world as a class, a channel for classes to communicate with the outside world by accessing members of the public type to complete the interaction with the class. For example, the teacher class's Givelesson () member function that represents the class behavior, which is the service it provides to the outside world, should be accessed by the outside world, so this member function should be set to public type.

Figure 6-9 Access levels

2. Type of protection

Members of the protection type are decorated with the keyword protected, with the same declaration format as the public type. Members of a protected type cannot be accessed outside of the class, but can be accessed within the class and derived classes that inherit from the class, and are primarily used to inherit attributes or methods to its next-generation subclasses. For example, for the M_strname member variable that represents the name attribute of the teacher class, no one wants to be modified by someone else's name, so you should restrict access to it, and obviously you can modify your name, so you can access the member variable inside the teacher class; If the teacher class has a derived class, such as a lecturer that represents a university teacher, we also hope that this member variable can be inherited to the derived class, so that its derived class also owns the member variable, which can be accessed. After this analysis, it is most appropriate to set the M_strname member variable to the protection type.

3. Private type

Members of private types are decorated with the keyword private, with the same declaration format as the public type. A member of a private type can be accessed only within the class, and all access from outside is illegal, so that the members of the class are completely hidden in the class, protecting the data and behavior in the class well. So hurry up and declare our purse as a private member so that the thief won't be able to access it.

It is important to note that if a class member does not explicitly describe its access level in the Class keyword definition, then by default it is a private type and the outside world is inaccessible, so the class is actually very "selfish" (conversely, in a class defined by a struct, The default access level is public type).

We rewrite the teacher class in the previous example to reflect the reality more realistically, based on the access control:

//the teacher class after access controlclassteacher{//Public Type Members//The outside world accesses these members to interact with the class to obtain the services provided by the class Public://The variable or function after the colon is modified by it//The constructor should be public so that the object of the class can be created by the outside world with the constructor functionTeacher (stringstrName): M_strname (strName) {//... ..    }    //The teacher wants to teach the students, it should be called by the outside, so this member function is public type    voidGiveelesson () {//within a class, you can access your own protection type and private type membersPreparelesson ();//Prepare lessons First, Access protection type memberscout<<"The teacher is in class. "<<Endl; M_nwallet+= -;//100 dollars A lesson, access to private type members    }    //We don't let people change their names, but we have to let people know our names.//for member variables that are only available for external read-only access,//can provide a public member function for read access by the outside world    stringGetName () {returnM_strname; }//Protection type Members//cannot be accessed by the outside world, but can be accessed by itself or inherited to the next class of subclasses,//for sub-class access at the next levelprotected://The subclass also needs to prepare for the lesson, so set the protection typevoidPreparelesson () {cout<<"The teacher prepares lessons. "<<Endl;}//Only You can modify your own name, subclasses also need such a property    stringM_strname;Private://Private Type   intM_nwallet;//wallets can only be accessed by themselves, so set to private type};

With access control, it is important to note that when accessing members of the Teacher class object, we can only access their public members in the outside world, and if we attempt to access their protection type or members of a private type, they will be ruthlessly rejected and eaten by others cold shoulder:

intMain () {//the constructor of the class is called when the object is created//in the teacher class, constructors are public types, so you can call directlyTeacher Mrchen ("Chenliangqiao"); //an external variable that holds the data obtained from the object    stringStrName; //read the member variable that gets the type of protection in the class through the public type member function of the classStrName =Mrchen.getname (); //Error: Unable to access the class's protection type and private type member directly//want to change my name? Ask me first, I promise not to .Mrchen.m_strname ="Wanggang"; //to take 200 bucks out of my purse.Mrchen.m_nwallet-= $; return 0;}

In the main function, we first create a teacher class object, which invokes its constructor, which requires the constructor to be of the public type. In the constructor, we will access the member variable m_strname, although it is a protected type, but it can be modified in the constructor of the class itself. On the other hand, in order for the outside world to be able to safely read the value of this member variable, we add a public type member function getname () for the teacher class, which allows the outside world to access the necessary data for members of the protected type in the class. In addition, the teacher class also provides a public-type Givelesson () function that can be called directly by the outside world to obtain class services provided by the teacher class. Inside the member function of this public type, we also access the protection type and the private type member in the class.

The above access is legitimate, but if you want to directly access a protected type or a member of a private type on the outside of the class, the compiler will help us detect this illegal access, generating a compile error that does not have access to protected or private type members. In this way, there is a compiler to help us watch, the thief will never try to move our purse.

By controlling the access of the members of the class, it plays a very good role in protecting the data and behavior, preventing the data from being modified arbitrarily, and restricting the unreasonable behavior of the outside world. If some member variables of an object allow external access due to the need for business logic (such as m_strname here), it is also advisable to use a method that provides a public interface to allow the outside world to access these member variables through the public interface, rather than directly setting these member variables to public types. In general, the member variables of a class should be set to protected or private types.

6.2.7 to access hidden information for a class in a friend

With the access control mechanism of class members, it is very good to realize the hiding of data and behavior, which effectively avoids the illegal access from outside and protects the security of data and behavior. However, this strict member access control is not the reason why, any access to the hidden information in the class (protection or private type members) is rejected, which naturally will be some reasonable access to the door, to the access of class members to bring some trouble. For example, sometimes you need to define a function that is not part of a class, but you need to frequently access the hidden information of a class, or you need to define a new class, for some reason this class needs to access the hidden information of another class, just like a real-world wife needs to access her husband's purse. In these cases, we need to directly access the class's protection or private type members from outside, but are blocked out of the door by strict member access control mechanisms.

There are exceptions to everything. C + + provides a friend mechanism in order to open a backdoor to the access control mechanism so that externally trusted functions or classes can access hidden information for a class. It uses the keyword "friend" to declare a function or class of the outside world as a friend or friend of a class, collectively referred to as friend. When you become a friend of a class, you can access the hidden information for the class.

1. Friend function

A friend function is actually a normal function that is defined outside a class and does not belong to any class. When the "friend" keyword is declared in the definition of a class, the function becomes a friend function of the class, and then it can directly access the hidden information of the class without being restricted by the access control of the class member. The syntax format for declaring a friend function in a class is as follows:

class class Name {    friend return value type function name (formal parameter list); // other declarations and definitions of the class...};

The declaration of the friend function is the same as the declaration of the ordinary member function of the class, except that the Friend keyword is modified before the function declaration and is defined outside the class and does not belong to this class. The declaration of a friend function is not affected by access control, it can be placed either in the private part of the class or in the public part of the class, and they are no different. In addition, a function can be a friend function for multiple classes at the same time, but it needs to be declared separately in each class.

2. Friend class

Like the friend function, a friend class is a separate generic class that is defined outside of a class. Because of the need to access the hidden information of this class, the "friend" keyword is used to declare it as a friend of this class, giving it the ability to access the hidden information of this class. After becoming a friend of this class, all member functions of the friend class become the friend function of this class, and the hidden information in this class can be accessed naturally.

In C + +, the syntax format for declaring a friend class is as follows:

class class Name {    class  friend class name; // other declarations and definitions of the class };

A friend class declaration is similar to a friend function declaration, which is not mentioned here. The only thing to note is the correlation between the two classes here, if we want class A to be able to access the hidden information of Class B, declare Class A as its friend class in Class B. This means that class A is a trusted "friend" of category B, so that class A can access the hidden information of Class B. In order to better understand the role of friends, or to see a practical example. Suppose there is a member variable in the previously defined teacher class M_nsalary records the teacher's salary information. Salary information is of course personal privacy needs to be protected, so its access control level is set to the protection type, only its own and derived subclasses can access:

class teacher{//  ... // Protection type of payroll information protected :     int m_nsalary;};

Setting m_nsalary as a protection type is a good way to secure your data. However, in some special cases, we have to have access to it in the outside world. For example, the Inland Revenue Department (denoted by the TAXATIONDEP Class) to check the teacher's salary income, of course, he should have the power and need to visit the teacher class M_nsalary this protection type of members, or the school would like to use the Adjustsalary () function to the teacher to adjust wages, The teacher naturally enjoyed it to visit M_nsalary members of this protection type. In this case, we need to declare the TAXATIONDEP class and the Adjustsalary () function as friends of the teacher class so that they can access the hidden information of the teacher class:

//teacher class with friendclassteacher{//declaring the Taxationdep class as a friend classFriendclassTAXATIONDEP; //declare the Adjustsalary () function as a friend functionFriendintAdjustsalary (teacher*teacher);//definition of other classes ...protected:    intM_nsalary;//members of the protection type};//friend functions that are defined outside the classintAdjustsalary (teacher*teacher) {    //A member of its protection type is accessed in the friend function of the teacher class M_nsalary    if(Teacher! = nullptr && Teacher->m_nsalary < +) {Teacher->m_nsalary + = -;//Pay rise       returnTeacher->M_nsalary;} return 0;}//Friend classclasstaxationdep{//other definitions of the class ... Public:    voidChecksalary (teacher*teacher) {        //access its protection type member in the friend class of the teacher class M_nsalary        if(Teacher! = nullptr && teacher->m_nsalary > +) {cout<<"The teacher should pay taxes ."<<Endl; }    }};

As you can see, when the teacher class uses the "friend" keyword to declare the adjustsalary () function and the Taxationdep class as its friend, you can directly access the member m_nsalary of its protection type in a friend, This is equivalent to opening a backdoor for friends, so that it can turn over access to control the wall and directly access to the hidden information of the class.

Although friends can bring us a certain convenience, but "back door" is not a very fair thing, in the use of friends, you should also pay attention to the following points:

L Friend relationships cannot be inherited. This is a good understanding that we are friends with a class (that is, a friend of a class) and it does not mean that we are also friends with this class of sons (derived classes).

The friend relationship is one-way and does not have commutative nature. For example, the Taxationdep class is a friend of the teacher class, tax officials can check the teacher's salary, but this does not mean that teacher class is also TAXATIONDEP class of friends, teachers can also check the wages of tax officials.

The declaration of a function or class as a friend means that the other party is audited and trustworthy, so it is authorized to access its own hidden information. This also suggests that it is necessary to audit a function or class before declaring it as a friend. Only trusted functions and classes can declare them as friends.

The use of friends does not destroy the encapsulation

In the friend function or friend class, we can directly access the class's protection or private type of members, this "backdoor" opened, many people worry that this will expose the hidden information of the class, destroying the encapsulation of the class. But the truth is that the rational use of friends, not only will not destroy the package, but will enhance the package.

In object-oriented design, we emphasize the design principle of "high cohesion and low coupling". In order to maintain the class's "high cohesion" when the different member variables of a class have two different lifecycles, we often need to split the member variables of these different lifecycles into two parts, that is, to split a class into two classes. In this case, the two parts that are split usually need to directly access each other's data. The safest way to achieve this is to make these two classes friends of each other. However, some "pros" take it for granted that friends break the encapsulation of a class, instead by providing the public get () and set () member functions to allow two parts to access the data to each other. In fact, they do not know that such an approach is destroying the package. In most cases, these get () and set () member functions are as bad as public data: They hide only the name of the private data and do not hide access to the private data.

The use of friends only exposes the hidden data of the class to the necessary clients, such as the teacher class simply exposes its hidden data to the TAXATIONDEP class, just so that the tax officer can know what its salary is. This is far more than using the public get ()/set () member function, which allows the world to know that its wages are much more secure and covert.

Hello, how does the C + + (35) class hide the money? 6.2.4 Copy Constructors

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.