[C ++ exploration tour] Part 2 Lesson 1: object-oriented exploration, the shocking inside story of string

Source: Internet
Author: User
Tags truncated

[C ++ exploration tour] Part 2 Lesson 1: object-oriented exploration, the shocking inside story of string

Introduction

1. Part 2TheLesson 1:Object-oriented research, the shocking inside story of string

2. Preview of the second lesson: set off the "class" header (1)

Object-oriented research, the shocking inside story of string

The first part of the course "C ++ exploration Journey" is Lesson 12th: a pointer to the question of who is competing with each other.

It is true that pointers are hard bones that are hard to chew. However, it may take a few days for you to cook it slowly. It can be a bowl of good bone soup, which is a major supplement to your C ++ level.

Okay, let's just wipe it out. We're officially in the second part of the C ++ exploration journey. Are you so excited? Do not continue to stream the just-wiped Khara.

This part of the course is called: C ++ object-oriented

Because we need to explore "Object-Oriented Programming" (OOP: Object-Oriented Programming ). This is a different programming mode from the past.

This method will not immediately make a revolutionary change to your program, and you may even feel that this model is useless at first.

So far, our programming model has been process-oriented. That is: If I want to implement any function, I need to write the function, declare the corresponding variable, and so on. For example, if I want to display a piece of information to the screen, I will create a function:

void showMessage(string message);

However, believe me: slowly, you will find that object-oriented programming patterns are more in line with human thinking than process-oriented. You will be able to better organize your code.

Note: The "object" mentioned next in this lesson sometimes refers to an object or a class. This is because we will learn the concept of "class" only in the next lesson. This course is not subdivided for the time being. We hope you can get a general idea of object-oriented.

Object... What's the purpose?

When you hear about object-oriented programming, the most curious word is "object.

You will think: Isn't this another mysterious design? Is it something that a sleep crazy programmer has come up?

Actually not. Our side is filled with objects: Your car is an object, your computer is an object, your mobile phone is an object, and so on.

In fact, everything we know can be seen as objects. Object-Oriented Programming is to operate on these elements called "objects" in code.

The following lists several common objects in programming:

A form: for example, a chat dialog box in QQ, the main interface of the drawing software.

One button: for example, the "Next" button when installing the software.

A character in the game.

A song, a video

After talking about this, what are the objects? Is it a new variable or a new function type?

No, no, no. Object is a new programming element!

Or more specifically, the object contains a mixture of variables and functions.

Don't be scared away from this sentence. Let's explore it a little bit.

Imagine... an object. Young man, I don't want you to think it's better to get married ~

We should try some practical images to help us understand them.

Imagine:

One day, a programmer decides to write a program with a graphical interface. This program can display the form on the screen, adjust the size of the form, move the form, delete the form, and draw various shapes in the form, and so on.

To implement these functions, the code is complicated: A lot of functions are required, and these functions are called each other. In addition, many variables are required, such as the form position (x and y coordinates), the width and height of the form, and so on.

This programmer spent a lot of time writing this program. The program is a bit complicated, but he finished it. In the end, his implemented code contains a lot of functions and variables.

When we saw his program for the first time, it was like looking at an experimental environment of a chemist. For example:

However, this programmer is still very satisfied with his program. He even wants to publish the program to the Internet so that everyone can use his program to create a form and use it directly, instead of writing code from scratch.

However, if you are not a chemistry expert, you may have to spend a lot of time figuring out how this pile of things works: Which function is called first? Which variable will be passed to which function to change the size of the form? In short, we are afraid to blow up the entire experiment environment.

After receiving suggestions and complaints from some users, the programmer decided to think for the users. He redesigned his code and changed from process-oriented to object-oriented.

This is like putting everything related to this chemistry experiment in a big box. This generous box is what we call "object ". For example:

In the middle, part of the generous box is set to transparent and intentionally, so that you can see the scene inside. Yes, all the devices in our chemistry experiment are in the big box. However, in reality, the generous box is completely opaque, and users cannot see what is inside it. For example:

This box contains functions and variables (those chemical instruments, test tubes, Beaker, etc.), but these elements are invisible to users.

In this way, users will no longer see piles of test tubes, Beaker, and other things that make them crazy. Outside the generous box, there are only some buttons we present to the user: one button is used to "Open the form", one button is used to "change the size of the form", and one button is used to "Close the form ", and so on. Users do not need to understand the operating principles in the generous box at all.

Therefore, programming in the object-oriented mode is:

Programmers write code (which may be complicated) and then install these complex code into a large box (object). Users cannot see the implementation details from the outside. Therefore, it is much easier for users who use this object to perform operations: Simply press the corresponding button and use the functions provided by the entire experiment environment without being proficient in chemistry.

Of course, the above metaphor is just a general concept.

We do not yet learn how to create objects in a broad sense. Instead, let's use an object first. In fact, we have already touched this object many times before, that is, string.

Before several lessons, we have already said that the string type is different from the ordinary int, bool, float, double type. These are the basic data types of C ++, which are used to store simple data.

But this is not true for string. In fact, it is an object. Many details are hidden behind the string type.

Uncover the mysteries behind string

Don't look at the string baby. It seems like a very serious big company boss Bruce Wayne (Bruce Wayne) during the day. In fact, he is Batman and there are many secrets behind it.

Thanks to the object-oriented programming model, we started to use string in the first part of the course. At that time, we did not know the secrets behind string. Let's unveil the mystery of string to see what the mechanism is.

For computers, the characters do not actually exist.

Why is the internal mechanism of string complicated?

First, we call string a "string", but the computer does not know the characters in string.

Remember? We say that a computer is a big calculator that only knows computing (English computer means "computer"). It only knows numbers!

However, if the computer only knows how to operate a number, how does it display so many characters on the screen? For example, you can use the screen to read a small article.

The pioneers of information technology have long come up with good ideas. You may have heard of ASCII (pronounced [aski]) tables. ASCII is the abbreviation of American Standard Code for Information Interchange, indicating "American Information Exchange Standard Code ".

An ASCII table is a table for conversion of numbers and characters. The following is a part of the ASCII table:

Number

Character

Number

Character

64

@

96

'

65

A

97

A

66

B

98

B

67

C

99

C

68

D

100

D

69

E

101

E

70

F

102

F

71

G

103

G

72

H

104

H

73

I

105

I

74

J

106

J

75

K

107

K

76

L

108

L

77

M

109

M

 

As we can see, uppercase letters A correspond to 65 and lowercase letters a correspond to 97. All English letters are included in this table.

That is to say: every time A computer sees the number 65, it will treat it as A capital letter?

No. Only when we ask the computer to translate a number to a character will it do it (it's pretty cute ). In reality, the computer determines how to "View" each number stored in the Variable Based on the declared variable type. The general rules are as follows:

  • For example, if we use int-type variables to store the number 65, the computer regards it as a number.

    On the contrary, if we use a char variable to store the number 65, the computer treats it as a character. The computer will say: Well, this is A capital letter. In fact, char is the abbreviation of character, indicating "character ". Used to store characters.

    Therefore, a char variable Stores numbers, but this number is interpreted as a character. However, a char variable can only store one character at a time. How can we store one sentence? We will continue to learn.

    A string is similar to a character array.

    Since char can only store one character (because the char size is one byte, that is, 8 bits, exactly the size of an English character, and the Chinese character occupies two bytes, programmers think of creating char arrays.

    We have learned the array, that is, the set of adjacent variables of the same type in the memory. Therefore, using character arrays to store a set of multiple characters (for example, one sentence) is a great choice. We usually call character arrays a "string ", is it a string of characters.

    Therefore, we only need to declare a char array as follows:

    char text[100];

    The char array 'text' can contain 100 characters. However, the array is static and the size is unchangeable. If you want to create a "dynamic array" whose size can be changed, you can use the vector type.

    For example:

    vector
       
         text;
       

    Theoretically, we can use static char arrays or dynamic char arrays to store a string of characters. However, this is inconvenient. Therefore, the C ++ designer decided to encapsulate string operations into an object, that is, string.

    Create and use a string object

    After that section, we learned that the Operation string is not simple. You need to create a char array. Each element in the array is a character. In addition, we need to create an array that is large enough to hold the strings we want to store. In short, there are many considerations.

    In this case, object-oriented programming can be used. Do you still remember the generous box in the picture above? String is such a "generous box ".

    Create a string object

    Creating an object is similar to creating a common variable (such as an int variable. For example:

    # Include
       
        
    # Include
        
         
    // The string header file must be introduced, because the string prototype is defined in using namespace std; int main () {string mString; // create a string type object mString return 0 ;}
        
       

    The above program is not complex. We mainly pay attention to the instruction for creating a string object in the sentence:

    string mString;

    So the method for creating an object is the same as creating a variable?

    Not all. There are several ways to create an object. We just demonstrated the simplest one. However, this method does not make much difference with creating a common variable.

    In this case, how do we distinguish between objects and common variables?

    To distinguish between variables and objects, we can refer to the naming rules:

    • The variable type starts with lowercase letters, for example, a common variable type int

      The object type starts with an uppercase letter, for example, Car.

      I know that you will definitely say: Do you think string doesn't start with lowercase letters? It is also the object type.

      I admit that this is an exception, and the above rules are not imposed on us. Obviously, programmers who implement string do not follow this rule.

      However, in most cases, the object type starts with uppercase letters.

       

      Initializes a string when it is declared.

       

      There are many ways to initialize an object when it is created:

       

      Int main () {string mString ("Hello! "); // Create a string-type object mString and initialize its value return 0 ;}

       

      Initialization in this way is the same as the basic variable types of C ++, such as int and double.


      In addition to the above method, we can also use the following method to initialize our string object:

       

      string mString = "Hello !";

       

      Since we have created a string object and assigned it a value of "Hello! ", We can print the content of this object.

       

      Int main () {string mString ("Hello! "); Cout <mString <endl; // display the string content, as if it is a string return 0 ;}

       

      Run, display:

       

      Hello!

       

      Change the value of a string after initialization.

       

      Now we have created our strings and assigned them the initial values. We can also change its value.

       

      int main(){ string mString("Hello !"); cout << mString << endl;  mString = "How are you ?"; cout << mString << endl; return 0;}

       

      To change the value of the string variable, we need to use the = (Value assignment ).

       

      The method demonstrated above is actually not much different from the previous method when we used the common variable type. Here I just want to show you the magic of object-oriented.

       

      You, that is, the user, just as if you have pressed a button. This button is used to issue a command: I want to extract the string content from "Hello! "Changed to" How are you? ".

       

      Although your commands are very short, the functions inside the string object are very busy after receiving the commands (which reminds me of Xiao Huang). They do the following in sequence:

       

      • First, check that "Hello!" is currently stored! "Is the char array adequate?" How are you? "This string.

        The answer is no. Therefore, they create a new char array with sufficient size to accommodate "How are you? "This new string.

        Once the new char array is created, the old array is destroyed.

        Then set "How are you? "The content of this string is copied to the new char array.

         

        See, this is a powerful feature of object-oriented programming: we have no idea how many things have happened in the string object.

         

        String concatenation

         

        Suppose we want to merge the contents of two strings into one string. Theoretically, this is not easy to implement. However, this mechanism has long been designed for the string object:

         

        int main(){ string mString1("Hello !"); string mString2("How are you ?"); string mString3; mString3 = mString1 + " " + mString2; cout << mString3 << endl; return 0;}

         

        It's easy, isn't it? You only need to use the plus sign to connect two strings. As for how many complicated operations are performed inside the string object, we "VIP users" don't care, and the right is so "willful "~

         

        String comparison

         

        Continue learning? This is a good idea.

         

        We can use = and! = Symbol to compare strings, indicating equal and unequal respectively.

         

        Int main () {string mString1 ("Hello! "); String mString2 (" How are you? "); If (mString1 = mString2) // obviously the two strings are not equal. The Condition Statement in parentheses is false {cout <" the two strings are equal. "<endl;} else {cout <" two strings are not equal. "<endl;} return 0 ;}

         

        In fact, within the string object, the comparison process is to compare two strings with one character and one character (using a loop ). However, we don't need to care about these details. It's just so cool.

         

        Some methods of string

         

        The function of the string object does not exist. There are also many useful methods, so we can see several common ones.

         

        Attributes and Methods

         

        As we have said before, an object contains variables and functions. However, since we want to learn object-oriented programming, we need to use more specialized terms.

         

        In the Object-Oriented field, variables in objects are called "attributes", and functions are called "methods ". It's just a different name.

         

        You can think of every method provided by the object as the buttons visible to users outside the generous box.

         

        Attributes and methods are also called "member variables" and "member functions ".

         

        To call methods in an object, we use a method you have seen:

         

        object.method()


        We use a vertex to connect an object with its member functions. This means that for this object, I call this method.

         

        Theoretically, we can also access member variables (attributes) in the same way ). However, in Object-Oriented Programming, we try to avoid direct access to our private member variables. There are many knowledge points about this, which we will discuss in future courses.


        The method for calling member functions and member variables is exclusive to objects. Common variable types cannot do this. This is also a good way to differentiate objects and variables in addition to names.

         

        Let's take a look at several member functions provided by string.

         

        Size Method

         

        Size indicates "size, size" in English. Therefore, the size method is used to obtain the size of the string object, that is, the number of characters contained in the object.

         

        The size method is easy to use and has no parameters:

         

        Int main () {string mString ("Hello! "); Cout <" the string length is "<mString. size (); return 0 ;}

         

        Run, display:

         

        The length of the string is 7.

         

        Erase Method

         

        The erase method is used to delete the content of a string, because erase indicates "delete, clear" in English.

         

        Int main () {string mString ("Hello! "); Cout <" the content of the string is: "<mString <endl; mString. erase (); cout <"after the erase method is called, the content of the string is:" <mString <endl; return 0 ;}

         

        Run, display:

         

        The content of the string is: Hello!

        After the erase method is called, the content of the string is:

         

        As we expected, after the erase method is called, the content of the string is cleared.

         

        In fact, the effect and

        ?

        mString = "";

         

        Is the same.

         

        Substr Method

         

        Substr is the condensation of sub and string. sub indicates "sub, sub", and string indicates "string". Therefore, as the name suggests, substr is a part of a string.

         

        The prototype of the substr method is as follows:

         

        string substr( size_type index, size_type num = npos );

         

        We can see that the return value of substr is also of the string type. It receives two parameters. One is index, which indicates the number of characters starting from the string, and the other is num, which indicates the number of characters to be truncated.

         

        In fact, more specifically, the substr method receives two parameters. The first parameter is required, and the second parameter is not required. That is to say, the first parameter must be provided. If the second parameter is not provided, num will take the default value. The default value is npos.

         

        Have you seen num = npos in the above prototype? This is a feature of C ++. It is called "default parameter ". That is to say, if this parameter is not assigned a value when the function is called, the parameter will take the default value after the equal sign (similar to the concept of "backup ).

         

        The value npos indicates that all the remaining characters are taken until the last one.

         

        For example:

         

        int main(){ string mString("Hello !"); cout << mString.substr(3) << endl; return 0;}

         

        Run, display:

         

        Lo!

         

        Because only one substr parameter is 3, the index of the first substr parameter is assigned 3, and the num of the second parameter is not assigned, the default value is used.

         

        Therefore, it indicates that the string is truncated from the fourth character of the mString until the end.

         

        Then try to assign a value to the second parameter num.

         

        int main(){     string mString("Surprise !");     cout << mString.substr(2, 4) << endl;         return 0;}

        Run, display:

         

        Rpri

         

        It is also easy to understand. We assign 2 and 4 values to index and num, respectively, so that we can intercept from the 3rd characters of mString and intercept 4 characters.

         

        We have learned before in the course of array. We can access a character of string type objects in an array-like way, using brackets []. For example:

         

        String mString ("Surprise! "); Cout <mString [3] <endl; // display 4th characters, that is, 'P'

         

        Well, this lesson is over.

         

        The main purpose of this course is not to fear object-oriented programming. After learning this course, do you already have a concept about object-oriented? In fact, before that, you have used objects, both string and vector are actually.

         

        I hope you are ready to create your own objects. It is said that programmers have no objects, so we will create a new programmer ~

         

        This is the goal of the next lesson.

         

        Summary

         

        1. Object-Oriented programming is a way to design code. Operations are called "object" elements.

          The implementation details in the object can be very complex, but the people who use the object do not need to care about these details, just need to know how to use it. This is a major advantage of object-oriented programming.

          An object is composed of attributes and methods, that is, variables and functions.

          We can call object methods to achieve various requirements.

          In memory, string operations are actually complicated. For the sake of our C ++ users, the C ++ designers designed us with a sophisticated object: string. We only need to use string to create string instances and operate on these strings without worrying about what happened in the memory.

          Part 2 Lesson 2 advance notice

          Today's class is here. Come on!

          In the next lesson, we will learn:Set off the "class" header (1)

    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.