Object-oriented (2), object-oriented
Last time, we learned how to create an object-oriented, "class" and define public attributes.
The public attribute defines the word "public ".
The public attribute indicates that the internally defined members are visible to all parts of the program. The Members here include: data members, member functions, and types.
That is to say, no matter what part of the program, you can directly access and modify the members of these class objects.
This means that everyone can modify the key data information in the class object, which is very insecure.
This time, let's take a look at the definition of private attributes in "class ".
The word "private" is defined as "private ".
When modifying a private property member, the member is only visible within the class and cannot be accessed outside the class.
Common private members include most of the variables, and some functions used for specific operation procedures that do not require the attention of class users
Class Student {
Private:
Int id;
Int age;
Public:
Int getID () {return id ;}
Int getAge () {return age ;}
Void setID (int newID );
Void setAge (int newAge );
};
In the above Code, we define two private members: id and age;
Two public members are defined: steID and setAge.
Void setID (int newID );
Void setAge (int newAge );
Next we will use the scope operator ":" After the class name to specify and define the class function in combination with the function name:
Void Student: setID (int newID) {id = newID ;}
Void Student: setAge (int newAge) {age = newAge <100? NewAge: 99 ;}
Then, call the above two functions in the main function and assign 1 and 16 to id and age respectively.
Because age is age, we add a condition statement when assigning values: {age = newAge <100? NewAge: 99 ;}
Determine whether the input age value is greater than 100. If it is less than 100, assign the original value to age. If it is greater than or equal to 100, assign 99 to age.
Then, the id and age values are exported from the private member.
Int main (){
Student tom;
Tom. setID (1); tom. setAge (16 );
Cout <tom. getID () <"" <tom. getAge ();
Return 0;
}