C + + Primer (4th edition)-Study notes-part 3rd: Classes and Data abstraction

Source: Internet
Author: User
Tags arithmetic operators bitwise operators class definition

12th Chapter Category
  1. Each class can have no members, or it can define multiple members, which can be data, functions, or type aliases.

  2. member functions must be declared inside a class, can be defined inside a class, or can be defined outside a class. If defined inside a class, it is an inline function by default.
    There are three types of inline functions :
    (1) defined directly within the class.
    (2) Within the class declaration, plus the inline keyword, defined outside the class.
    (3) Within the class declaration, defined outside the class, plus the inline keyword. Note: In this case, the definition of the inline function should usually be placed in the same header file as the class definition, not in the source file. This is to ensure that the definition of an inline function is visible in every source file that invokes the function.
  3. A const member cannot change the data member of the object it is manipulating. The const keyword for the const member function must appear in both the Declaration and the definition , and a compile-time error occurs if it appears only in one place.
    Double Avg_price () const;

  4. Why is the class defined in the header file?
    When the closing curly brace is encountered, the definition of the class ends. Once you have defined a class, you know the members of the class, storage space. In a given source file, a class can only be defined once. If you define a class in more than one file, the definitions in each file must be exactly the same.
    Defining a class in a header file ensures that the class is defined in the same way for each file that uses the class (to use that class, which must include the header file of the Class).
  5. Avoid multiple occurrences of the same file, guaranteeing that the definition only occurs once, even if the header file is included multiple times in the same file.
    (1) UseHeader File Protector (#ifndef ... #endif)
    #ifndef __somefile_h__
    #define __somefile_h__
    ...//Declaration, definition statement
    #endif
    Pros:#ifndef的方式受C/c++ language Standard support. It does not only guarantee that the same file will not be included more than once, but also that two files (or snippets) with exactly the same content will not be included accidentally.
    Cons: if the macro name in a different header is accidentally "crashed", it may cause you to see that the header file exists, and the compiler insists it cannot find the state of the statement. (2) Use#pragma once
    #pragma once
    ...//Declaration, definition statement
    #pragma once is generally guaranteed by the compiler: the same file will not be included multiple times. Note that the "same file" here refers to a physical file, not two files of the same content. You cannot make a pragma once declaration for a piece of code in a header file, but only for a file. Pros: You don't have to bother to think of a macro name, of course, there will be no macro name collision caused by the strange problem, the compilation speed of large projects also increased some. Cons: If there are multiple copies of a header file, this method does not guarantee that they will not be included repeatedly. Of course, this repetition is easy to detect and correct, compared to the "no claims" issue caused by the macro name collision.

  6. class  screen ; The
    declares a class, but does not define it. After the declaration, only the screen is a class name but does not know which members are included. It can only be used in a limited way, for example: is a class name, but does not know which members are included. It can only be used in a limited way, for example: defines a pointer or reference to that type, declaring (not defining) using the type as a function of the formal parameter type or return type. For example:
    void Test1 ( screen & A) {};void Test1 ( screen * a) {};-
  7. Class definition (define)
    Before you create an object of a class, you must define the class completely, not just the class. Therefore, a class cannot have a data member of its own type, but it can contain pointers or references to this class.
    Class Linkscreen
    {
    screen window;
    Linkscreen* NEXT;
    linkscreen* prev;
    }; //Note that semicolons cannot be lost

  8. Class object
    When you define a class, no storage allocations are made.
    The storage space is allocated only when the class object is defined. such as: Linkscreen SCR;

  9. Why does the definition of a class end with a semicolon?
    Because a list of object definitions can be followed after the class definition. The definition must end with a semicolon:
    Class Sales_item {/* ... */};
    Class Sales_item {/* ... */} accum, trans;

  10. mutable Variable data members
    mutable mutable data members are never const, so the const member function can change mutable members.

  11. Class scope
    Each class defines its own scope and unique type.
    The scope of a class includes the inside of the class (within curly braces), the parameter table (within parentheses) of the member function outside the class, and the body of the function (within curly braces).
    Note: The return type of a member function is not necessarily in the class scope . The class name:: To determine whether the scope of the class,:: Before the scope of the class,:: After the scope of the class. For example
    Char Screen::get (index R, index c) const
    {
    Index row = r * Width; Compute the row location
    return Contents[row + c]; Offset by c to fetch specified character
    }
    Screen:: The previous return type is not in the scope of the class, screen:: After the function name starts to the function body is the scope of the class.
  12. constructor function
    Constructors are special member functions that ensure that the data members of each object have appropriate initial values.
    The constructor name is the same as the class name, you cannot specify a return type (and you cannot define a return type of void), and you can have 0-n parameters.
    When you create an object for a class, the compiler runs a constructor.

  13. constructor Initialization
    Sales_item::sales_item (const string &book): ISBN (book), Units_sold (0), Revenue (0.0)  {} 
    Constructor initialize list The begins with a colon, followed by a comma-delimited list of data members followed by an initializer in parentheses. Constructor initialization is specified only in the definition of the constructor, not in the declaration. The
    can assume that the constructor is executed in two stages: (1) The initialization phase, and (2) the normal calculation phase. The initialization list belongs to the initialization stage (1), and all statements in the constructor function body belong to the calculation phase (2). The initialization list is performed before the body of the constructor. a data member of a class type is always initialized during the initialization phase regardless of whether the member is explicitly initialized in the constructor initialization list.
      
  14. Initialization of data members of a class object
    Each member that is not explicitly mentioned in the constructor initialization list of Class A is initialized with the same rules as the initialization variable. For example, a data member of a class type that runs the default constructor for that type to initialize. The initial value of a member of a built-in or composite type depends on the scope of the class object: not initialized in the local scope, initialized to 0 in the global scope. Suppose there is a Class A,
    Class A
    {
    Public
    int ia;
    b b;
    };
    Class A; Regardless of whether a is in local scope or global scope, B is initialized with the default constructor of Class B, the initialization of IA depends on the scope of a, a at the local scope, IA is not initialized, a in global scope, IA initialization 0.
    You can initialize objects of a const object or reference type, but you cannot assign values to them. The initialization is done before the function body of the constructor is started. The only chance to initialize a const or reference type data member is in the constructor initialization list, which does not work in the constructor function body. Members of a class type that do not have a default constructor, and members of a const or reference type, must complete initialization in the initialization list.

  15. The order in which member initialization is initiated
    Each member can be specified only once in the constructor initialization list.
    The order in which members are initialized is the order in which members are defined, regardless of the order in which they are initialized.

  16. An initializer can be any expression
    Sales_item (const std::string &book, int cnt, double Price): ISBN (Book), Units_sold (CNT), Revenue (CNT * Price ) { }

  17. Initialization of a data member of a class type
    When you initialize a member of a class type, you can use any constructor of that type to specify the argument and pass it to a constructor of the member type.
    Sales_item (): ISBN (9 '), Units_sold (0), Revenue (0.0) {}

  18. Default constructor
    The default constructor is used when an object is defined without an initialization. A constructor that provides default arguments for all parameters also defines a default constructor.
    The compiler automatically generates a default constructor only if a class does not have a constructor defined. Even if a class defines only one constructor, the compiler will no longer generate a default constructor.
    Recommendation: If other constructors are defined, a default constructor is also provided.
    If a class contains a member of a built-in or composite type (such as int& or string*), it should define its own constructor to initialize those members. Each constructor should provide an initialization for each member of a built-in or composite type.

  19. Implicit class-Type conversions
    A constructor that contains only a single parameter can implement an implicit conversion from the formal parameter type to the class type.
    Class Sales_item {
    Public
    Sales_item (const std::string &book = ""): ISBN (Book), Units_sold (0), Revenue (0.0) {}
    };
    String null_book = "9-999-99999-9";
    ITEM.SAME_ISBN (null_book); We have implemented implicit conversions from Null_book to Sales_item types.

  20. The
  21. suppresses implicit conversions defined by the constructor
    by declaring the constructor as   explicit , To prevent the use of constructors in contexts where implicit conversions are required:  
    class Sales_item {
         public:
             //default argument for book is the empty string
               explicit  sales_item (const std:: String &book = ""):
                        ISBN (book), Units_sold (0), Revenue (0.0) {}
              Explicit Sales_item (Std::istream &is);
            /As before
        }; 
    Typically, The single-parameter constructor should be explicit unless there is a clear reason to define implicit conversions. Setting the constructor to explicit avoids errors, and when the conversion is useful, the user can explicitly construct the object.

  22. Friend Yuan
    The friend mechanism allows a class to grant access to its non-public members to the specified function or class. A friend can only appear anywhere inside the class definition. Friends are not members of the class that is granted a friend relationship, so they are not affected by the access control that is part of the declaration. It is recommended that friend declarations be placed in groups at the beginning or end of the class definition .

    Make a member function of another class A friend
    For example, in Class A to make the member function C in class B a friend, you must first define Class B (Declare function C in B), then define Class A, declare the member function C of B in Class A as friend, and finally define C.

  23. Static member Variable
    A static data member is an object associated with a class and is not associated with an object of that class.
    Static members follow normal public/private access rules.
  24. There are three advantages to using static members instead of global objects.
    (1) The name of the static member is in the scope of the class, so you can avoid conflicts with other classes ' members or global object names.
    (2) encapsulation can be implemented. A static member can be a private member, and a global object may not.
    (3) It is easy to see that a static member is associated with a particular class through a reading program. This visibility can clearly show the programmer's intentions.

  25. Static member function
    You need to add the static keyword when declaring a function inside a class, but it is not necessary to define a function outside of the class.
    Because static members are part of a class but are not part of any object, there are several features:
    1) The static function does not have this pointer
    2) static member function cannot be declared as const
    3) The static member function cannot be declared as a virtual function

  26. Static data member
    Static data members can be declared as arbitrary types, which can be constants, references, arrays, class types, and so on.
    The static data member must be defined outside the body of the class definition (exactly once) and should be initialized at the time of definition. It is recommended to define the name in the source file of the class, which is the same file as the definition of the non-inline function of the class. Note that the definition also takes the class type + "::"
    Double account::interestrate = 0.035;

  27. Special Integer const static member
    Integer const static data members can be initialized directly in the class's definition body, for example:
    static const int period = 30;

  28. static data member can be the class type to which the member belongs. A non-static member can only be a pointer or reference to its own class object:  
    Class bar  {
          public:
            //...
         Private:
             static  bar  mem1; OK
             Bar *mem2;      //OK
             Bar mem3;       //Error
    } ;  

  29. Non-static data members cannot be used as default arguments, and static data members can be used as default arguments.
    Class Screen {
    Public
    Bkground refers to the static member
    Declared later in the class definition
    screen& Clear (char = bkground);
    Private
    static const char bkground = ' # ';
    };

13th. Copy Control
  1. Copy constructor
    A copy constructor is a special constructor, with only 1 formal parameters, which is a reference to the class type (Common Const & adornments). When you define a new object and initialize it with an object of the same type, the copy constructor is used explicitly. When you pass an object of that type to a function or function that returns an object of that type, the copy constructor is implicitly used.

  2. Destructors
    Destructors are complementary to constructors: destructors are automatically applied when objects that are out of scope or dynamically allocated are deleted. Destructors can be used to dispose of resources that are acquired during the construction of an object or during the life of an object. The compiler automatically executes destructors for non-static data members of the class, regardless of whether the class defines its own destructor.

  3. the copy constructor, assignment operator, and Destructor are always referred to as replication controls . The compiler automatically implements these operations, but the class can also define its own version.

  4. C + + supports two types of initialization: direct initialization and replication initialization. Direct initialization puts the initialization in parentheses, and the copy initialization uses the = symbol.
    For built-in types, such as int, double, and so on, there is no difference between direct initialization and replication initialization.
    For a class type: Direct initialization directly invokes the constructor that matches the argument; Copy initialization uses the specified constructor to create a temporary object and then copies that temporary object to the object being created with the copy constructor . Direct initialization is faster than replication initialization.

  5. Formal parameters and return values
    Copied by the copy constructor when the formal parameter or return value is a class type.

  6. Initializing container elements
    The copy constructor can be used to initialize the elements in the sequential container. For example:
    Vector<string> Svec (5);
    The compiler first creates a temporary value using the string default constructor, and then uses the copy constructor to copy the temporary values to each element of Svec.

  7. Constructors and array elements
    If no element initialization is provided for the class-type array, each element is initialized with the default constructor.
    If you provide an explicit element initializer with an array initialization list that is surrounded by regular curly braces, use copy-initialization to initialize each element. Creates an element of the appropriate type based on the specified value, and then copies the value to the appropriate element with the copy constructor:
    Sales_item primer_eds[] = {string ("0-201-16487-6"),
    String ("0-201-54848-8"),
    String ("0-201-82470-1"),
    Sales_item ()
    };

  8. Synthetic copy Constructors
    If we do not define a copy constructor, the compiler will synthesize one for us.
    The behavior of the composite copy constructor is to perform a member-by-instance initialization to initialize the new object to a copy of the original object.
    Initialize by member: the composite copy constructor copies the values of the built-in type members directly, and the class type members use the copy constructor of the class to replicate.
    exception: If a class has an array member, the composition copy constructor copies the array. When you copy an array, the composite copy constructor copies each element of the array.

  9. Define your own copy constructor
    (1) A class that contains only members of a class type or a built-in type (but not a pointer type), you do not have to explicitly define a copy constructor, or you can copy.
    (2) Some classes must control what happens when the object is copied. For example, a class has a data member that is a pointer, or there are members that represent other resources that are assigned in the constructor. Other classes must do some specific work when creating new objects. In both cases, you must define your own copy constructor.

  10. Prohibit copying
    Some classes require a complete ban on replication. For example, the Iostream class would not allow replication.
    To prevent replication, the class must explicitly declare its copy constructor as private.

  11. Most classes should define copy constructors and default constructors
    In general, it is a good idea to explicitly or implicitly define default constructors and copy constructors. The default constructor is synthesized only if no other constructors exist.
    If you define a copy constructor, you must also define a default constructor.

  12. Assignment operator
    As with the copy constructor, if the class does not define its own assignment operator, the compiler will synthesize one.
    sales_item& operator= (const Sales_item &);

  13. Synthetic assignment operators
    The synthetic assignment operator assigns values individually: Each member of the right operand object is assigned to the corresponding member of the left operand object. In addition to the divisor group, each member is assigned in the usual manner of the owning type. For arrays, assign values to each array element.

  14. Replication and assignment are often used together
    In general, if a class requires a copy constructor, it will also require an assignment operator.

  15. Destructors
    One of the uses of constructors is to get resources automatically; In contrast, one of the uses of destructors is to reclaim resources. In addition, destructors can perform arbitrary actions that the Class designer wants to perform after the class object has been used.

  16. When do I call destructors?
    The destructor is called automatically when the class object is revoked (destroyed).
    Variables (class objects) should be automatically revoked (destroyed) when they go out of scope.
    A dynamically allocated object (new A) is revoked (destroyed) only if a pointer to that object is deleted.
    When you revoke (destroy) a container (either a standard or a built-in array), the destructor for the class-type element in the container is also run ( the elements in the container are always withdrawn from the back -and-forth).

  17. When do I write an explicit destructor?
    If a class needs to define a destructor, it also needs to define the assignment operator and the copy constructor, which is often called the three rules: If the class requires a destructor, all three copy control members are required.

  18. Composition destructor
    The composition destructor revokes each non-static member in reverse order when the object is created, so that it revokes the member in the reverse sequence of declaring the member in the class. For each member of a class type, the composition destructor calls the member's destructor to undo the object. The composition destructor does not delete the object that the pointer member points to. So, if you have a pointer member, be sure to define your own destructor to remove the pointer.
    An important difference between a destructor and a copy constructor or assignment operator: Even if we write our own destructor, the composition destructor is still running.

  19. Most C + + classes use one of the following three methods to manage pointer members:
    1) The pointer member takes the normal pointer type behavior. Such a class has all the flaws of the pointer but does not require special replication control.
    2) class can implement so-called "smart pointer" behavior. The object that the pointer points to is shared, but the class prevents the dangling pointer.
    3) class takes the value-type behavior. The object that the pointer points to is unique and is managed independently by each class object.

  20. Objects with pointer members generally need to define replication control members.
    In order to manage classes with pointer members, you must define three copy control members: Copy constructors, assignment operators, and destructors. These members can define pointer-type behavior or value-type behavior for pointer members.

  21. Smart pointers
    The difference between a smart pointer class and a class that implements normal pointer behavior is that a smart pointer typically accepts a pointer to a dynamically allocated object and is responsible for deleting the object, and the user assigns the object, but the smart pointer class removes it, so the smart pointer class needs to implement a copy control member to manage pointers to its shared objects. The shared object cannot be deleted until the last smart pointer to the shared object has been destroyed, and using a count is the most common way to implement a smart pointer class.

  22. Value type class
    The so-called value class, a class with value semantics, is characterized by the fact that when a copy of the object is made, a different new copy is obtained, and changes made to the new copy do not affect the original object.

14th Chapter overloaded operators and Conversions
    1. What are the similarities and differences between overloaded operators and built-in operators?
      Same: operator precedence, binding, or number of operands are the same
      Different: Overloaded operators must have at least one class type or operand of an enumeration type; overloaded operators do not guarantee the order in which operands are evaluated, in particular, the operands of the built-in logical and, logical, or comma operators are not guaranteed to be evaluated.

    2. Class members and non-member overloaded operators
      Overloaded unary operator If there is no (explicit) parameter as a member function, there is a formal parameter as a non-member function. Similarly, the overloaded two-tuple operator has a formal parameter when defined as a member, and two parameters when defined as a non-member function.

    3. The principle of setting an operator to a class member or a normal non-member function:
      • Operators such as assignment (=), subscript ([]), Call (()), and member access arrows must be defined as members, and those operators defined as non-member functions will be marked as errors at compile time.
      • Like assignment, a compound assignment operator should typically be defined as a member of a class, unlike an assignment, which does not necessarily have to be done, and a compilation error does not occur if a non-member compound assignment operator is defined.
      • Some other operators that change the state of an object or are closely related to a given type, such as self-increment, self-subtract, and dereference, are usually defined as class members.
      • Symmetric operators, such as arithmetic operators, equality operators, relational operators, and bitwise operators, are best defined as ordinary non-member functions.

C + + Primer (4th edition)-Study notes-part 3rd: Classes and Data abstraction

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.