Important Notes on C ++ programming ideology (I) and key points on programming ideology

Source: Internet
Author: User

Important Notes on C ++ programming ideology (I) and key points on programming ideology

  1. The most important difference between C ++ and C ++ pointers is that C ++ is a language with higher type requirements. Justvoid *This is even more prominent. C. Although it is not allowed to assign a type pointer to another typevoid *. For example:

       
       
    1. bird* b;
    2. rock* r;
    3. void* v;
    4. v = r;
    5. b = v;

    C ++ does not allow this. Its compiler will provide an error message. To do this, you must explicitly use ing to notify the compiler and readers.

  2. Parameter transfer criteria
    When passing parameters to a function, people are used to passing them through constant references. This simple habit can greatly improve the efficiency: the value passing method needs to call constructor and destructor, however, if you do not want to change the parameter, you can pass it through constant reference. It only needs to push the address to the stack. In fact, there is only one situation where it is not suitable for transferring addresses. This is the only safe way to pass values. Otherwise, the object will be damaged (instead of modifying external objects, this is not what the caller usually expects ).

  3. C ++ Access Control: public, private, and protected
    Specifically, protected has different meanings only in inheritance. Otherwise, it is the same as private, that is, the two are only different: the inherited structure can access the protected member, but cannot access the private member.

  4. Note

       
       
    1. struct X; // Declaration(incomplete type spec)
    2. struct Y
    3. {
    4. void f(X *memx);
    5. void g(X memx); // not allowed, the size of X is unknown.
    6. };

    Here f (X *) references the address of an X object, which is no problem, but if it isvoid g(X memx);The compiler reports an error. This is critical because the compiler knows how to pass an address. This address is of a certain size, rather than the type of the object to be passed. If you try to pass the entire object, the compiler must know all the definitions of X to determine its size and how to pass it. This makes it impossible for programmers to declare a file similar to Y: g (X).

  5. Is C ++ pure?
    If a function of a class is declaredfriendIt means that it is not a member function of the class, but can modify the private member of the class, and it must be included in the class definition, therefore, we can regard it as a privileged function. This type of definition provides information about permissions. We can know which functions can change the private part of the class. Therefore, C ++ is not a fully object-oriented language, but a hybrid product.friendKeyword is used to solve some of the unexpected problems. It also shows that the language is not pure. After all, the C ++ language is designed to be practical, not to pursue the ideal abstraction.

  6. Manipulator of the C ++ input/output stream includes endl, flush, ws, and hex.

       
       
    1. Cout <flush; // clears the stream
    2. Cout
    3. Cin> ws; // skip Spaces

    Iostream. h also includes the following operators:

    Operator Function
    Showbase/noshowbase When an integer is printed, the base number (decimal, octal, and hexadecimal) is indicated. The format used can be read by the C ++ compiler.
    Showpos/noshowpos Display positive value symbol plus (+)
    Uppercase/nouppercase Display the uppercase letter A-F representing the hexadecimal value and E in the scientific notation
    Showpoint/noshowpoint Indicates the decimal point of the floating point value and the following zero
    Skipws/noskipws Skip blank characters in the input
    Left Align left and fill right
    Right Right alignment, left Filling
    Internal Fill in between the pilot or base indicator and Value
    Scientific Use scientific notation
    Fixed Setprecision () or ios: precision () sets the number of digits after the decimal point

    How can we create our own operators?
    We may want to create our own operators, which is quite simple. An operation operator without parameters such as endl is just a function that uses an ostream reference as its parameter. The statement for endl is:

       
        
    1. ostream& endl(ostream&);

    Example: generate a line feed without refreshing the stream. It is considered that nl is better than endl because the latter always clears the output stream, which may cause execution failure.

       
        
    1. ostream& nl(ostream& os) {
    2. return os << "\n";
    3. }
    4. int main() {
    5. cout << "newlines" << nl << "between" << nl << "each" << nl << "word" << nl;
    6. return 0;
    7. }
  7. The difference between const in C language and const in C ++:
    Constants were introduced in the early C ++ version, when the standard C Specification was being developed. At that time, constants were considered a good idea and included in C. However, const in C means "a common variable that cannot be changed". In C, it always occupies storage and its name is a global character. The C compiler cannot regard const as a constant during compilation. In C, if you write:

       
        
    1. const bufsize=100;
    2. char buf[bufsize];

    Although it seems to have done a reasonable thing, this will produce an incorrect result. Because bufsize occupies a certain place of storage, the C compiler does not know its value during compilation. In C, you can choose to write as follows:

       
        
    1. const bufsize;

    It is wrong to write it in C ++, while the C compiler uses it as a declaration, which indicates that there is storage allocation elsewhere. Because C's default const is an external connection, C ++'s default cosnt is an internal connection, so if you want to do the same thing in C ++, you must use extern to change the connection to an external connection:

       
        
    1. extern const bufsize;//declaration only

    This method can also be used in C.
    Note: using the qualifier const in C language is not very useful, even in a constant expression (which must be obtained during compilation); To use a named value, using const is not very useful. C forces programmers to use # define in a Preprocessor.

  8. Const and enum in the class
    Is there any problem in writing the following statements? :

       
        
    1. class bob {
    2. const size = 100; // illegal
    3. int array[size]; // illegal
    4. }

    Of course, the compilation fails. Why? Because const allocates storage space in class objects, the compiler cannot know what const content is, so it cannot be used as a constant during compilation. This means that for a constant expression in a class, const does not work as it does in C.

    The const in the class indicates "this value remains unchanged during the life cycle of this specific object, rather than for the entire class ". So how to create a class constant that can be used in a constant expression?
    A common method is to use a unlabeled enum without an instance. All values of the enumeration must be created during compilation. It is partial for the class, but the constant expression can get its value. As a result, we generally see:

       
        
    1. class bob {
    2. enum { size = 100 }; // legal
    3. int array[size]; // legal
    4. }

    Using enum does not occupy the storage space of objects. Enumeration constants are fully evaluated during compilation. We can also explicitly set the enumerated constant value:enum { one=1,two=2,three};

  9. Const member functions in the class

       
        
    1. class X {
    2. int i;
    3. public:
    4. int f() const;
    5. }

    Here f () is a const member function, indicating that only the const class object can call this function (the const object cannot call non-const member functions ), if we change any member of an object or call a non-const member function, the compiler sends an error message.
    The const keyword must appear in the definition in the same way; otherwise, the compiler regards it as a different function:

       
        
    1. int X::f() const { return i;}

    Any function that does not modify member data should be declared as a const function, so that it can be used by the const object.
    Note: const and destructor are not const member functions, because they always modify objects during initialization and cleaning.

    Extended: how to modify a member in the const member function-by bit and by member const

    What if we want to create a const member function but still want to change some data in the object? This is related to the difference between the bitwise const and the member const. The bitwise const indicates that each bit in the object is fixed, so each bit of the object is never changed. By member const, although the entire object is conceptually unchanged, a Member may change. When the compiler notifies a const object, it protects the object.

    Here we will introduce two methods to change data members in the const member function.

    • The first method is called "forced conversion const ". It is executed in a rather strange way. Take this (this keyword generates the address of the current object) and forcibly convert it into a pointer to the current type of object. It seems that this is a required pointer, but it is a const pointer. Therefore, we should forcibly convert it into a normal pointer so that constants can be removed in the operation. The following is an example:

           
            
      1. class Y {
      2. int i, j;
      3. public:
      4. Y() { i = j = 0; }
      5. void f() const;
      6. };
      7. void Y::f() const {
      8. //! i++; // error
      9. ((Y*)this)->j++; // ok , cast away const feature.
      10. }

      This method is feasible and can be seen in the previous program code, but this is not the preferred technology. The problem is: this is not decorated with const, which is hidden in the member function of an object. In this way, if the user cannot see the source code (and find the place where this method is used ), I don't know what happened.

    • The second method is recommended, that is, using keywords in the class declaration.mutableTo specify that a specific data member can be changed in a const object.
           
            
      1. class Y {
      2. int i;
      3. mutable int j;
      4. public:
      5. Y() { i = j = 0; }
      6. void f() const;
      7. };
      8. void Y::f() const {
      9. //! i++; // error
      10. ((Y*)this)->j++; // ok , mutable.
      11. }
  10. Volatile keywords
    The syntax of volatile is the same as that of const, but volatile means that "beyond the scope recognized by the compiler, this data can be changed ". Somehow, the environment is changing data (possibly through multi-task processing), so volatile tells the compiler not to make any assumptions about the data without authorization-this is especially important during optimization. If the compiler says, "I have read the data into the register and have no contact with the register ". Generally, it does not need to read the data again. However, if the data is modified by volatile, the compiler cannot make such assumptions, because it may have been changed by other processes. It must re-read the data rather than optimize the code.

    Note:

    • Just like creating a const object, programmers can also create a volatile object, or even create a const volatile object. This object cannot be changed by programmers, but can be changed through external tools.
    • Like const, we can use volatile for data members, member functions, and objects, and can only call volatile member functions for volatile objects.
    • The syntax of volatile is the same as that of const, so they are often put together for discussion. To indicate that either of the two can be selected. They are collectively referred to as the c-v qualifier.

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.