Class Definition details in C ++
Member variables
Each class can have no members or multiple members. The members can be data, functions, or type aliases.
A class can contain several public, private, and protected parts. Members defined in the public part can be accessed by all code using this type; Members defined in the private part can be accessed by other class members. Protected can be accessed by the quilt class.
Constructor
A function that has the same name as a class and has no return value. It is used to construct an object.
Generally, an initialization list is used to initialize data members, as follows:
Sales_item (): units_sold (0), revenue (0.0 ){}
Member Functions
In a class, declaring a member function is required, while defining a member function is optional.
The default function defined in the class is inline.
The member functions defined outside the class must specify that they are in the scope of the class. The definition of Sales_item: avg_price uses the scope operator to indicate that this is the definition of avg_price function in the Sales_item class.
After adding the const to the form parameter table, it can become a constant member function. The value of the member variable cannot be modified in this function, for example, double avg_price () const;
Const must appear in the declaration and definition. If one item appears, a compilation error occurs.
Ps: const member functions can distinguish between overloaded functions
Display the specified inline member function
You can specify a member as inline within the class definition body as part of its declaration. Alternatively, you can specify inline on the Function Definition outside the class definition. It is valid to specify the inline in the declaration and definition. One advantage of defining inline externally in a class is that it makes the class easier to read. Like other inline functions, the definition of inline member functions must be visible in each source file that calls the function. Inline member functions not defined in the class definition body should be defined in the same header file with the class definition.
Define a class
Class Test {
};// Note that there must be no fewer semicolons
Declare a class
Class Test;// Forward Declaration
The class can be defined only after the class definition body is completed. Therefore, the class cannot have data members of its own type. However, when a class name appears, it can be considered declared. Therefore, the data member of the class can be a pointer or reference to its own type, as shown below:
Class LinkScreen {
Screen window;
LinkScreen * next;
LinkScreen * prev;
};
The class definition is ended with a semicolon. A semicolon is required because an object definition list can be added after the class definition. The definition must end with a semicolon:
Class Sales_item {/*...*/};
Class Sales_item {/*... */} accum, trans;
Ø implicit this pointer
A member function has an additional implicit parameter, that is, a pointer to the class object. This implicit parameter is named this and bound to the object that calls the member function. A member function cannot define this parameter, but is implicitly defined by the compiler. The function body of a member function can explicitly use the this pointer, but this is not required (for example, return * this ;). If there is no limit on the reference of class members, the compiler will process this reference as a reference through the this pointer.
Ø the const member function returns * this
In a common non-const member function, the type of this is a const pointer pointing to the class type. You can change the value pointed to by this, but cannot change the address saved by this. In a const member function, this is a const pointer to a const class object. You cannot change the object that this points to or the address that this stores.
* A common reference to a class object cannot be returned from the const member function. The const member function can only return * this as a const reference. ****
Ø const-based Overloading
A member function can be reloaded based on whether the member function is const. Similarly, a function can be reloaded based on whether a pointer or referenced parameter points to const. A const object can only use a const member. Non-const objects can use any member, but non-const versions are a better match.
Variable data member
Mutable data member cannot be a const, even if it is a member of a const object. Therefore, the const member function can change the mutable member. To declare a data member as mutable, you must put the keyword mutable before the member declaration:
Mutableint num;
The form parameter table and function body are in the class scope.
In a member function defined outside the class, both the form parameter table and the member function body appear after the member name. These are defined in the class scope, so you can reference other members without limitation.
CharScreen: get (index r, indexc) const
{
Index row = r * width; // compute the row location
Return contents [row + c]; // offset by c to fetch specifiedcharacter
}
This function uses the index type defined in Screen to specify its parameter type. Because the form parameter table is in the scope of the Screen class, you do not need to specify that we want Screen: index. What we want is defined in the current class scope, which is implicit. Similarly, index, width, and contents are the names declared in the Screen class.
The function return type is not necessarily in the class scope.
Compared with the parameter type, the return type appears before the member name. If a function is defined outside the class definition body, the type name is returned outside the class scope. If the returned type uses a type defined by the class, you must use a fully qualified name. For example, consider the get_cursor function:
ClassScreen {
Public:
Typedef std: string: size_type index;
Index get_cursor () const;
};
Inline Screen: index Screen: get_cursor () const
{
Return cursor;
}
Ø Constructor
Sales_items (); the object is in the stack Area
Sales_item * p = new Sales_item (); the object is in the heap Area
Ps: const cannot be declared as const.
Sales_item () const; // error
Pps: similar to other functions, constructor has the name (same as the class name), shape parameter table, and function body. The difference is that there is no return value, return type, it also contains a list of constructors for initialization:
Sales_item: Sales_item (conststring & book): isbn (book), units_sold (0), revenue (0.0 ){}
Equivalent
Sales_item: Sales_item (conststring & book)
{
Isbn = book;
Units_sold = 0;
Revenue = 0.0;
}
Note: This constructor assigns values to members of the Sales_item class, but does not perform Explicit initialization. Whether or not there is an explicit initialization type, you need to initialize the isbn member before executing the constructor. This constructor implicitly uses the default string constructor to initialize isbn. When executing the constructor function, the isbn member already has a value. This value is overwritten by the value assignment in the constructor body.
In terms of concept, constructor can be considered to be executed in two stages: (1) initialization stage; (2) normal computing stage. The computing phase consists of all the statements in the constructor body.
Whether or not the Members are explicitly initialized in the constructor initialization list, data members of the class type are always initialized in the initialization phase. Initialization occurs before the computing phase starts. Each member not explicitly mentioned in the constructor initialization list uses the same rule as the initialization variable for initialization. Run the default constructor of this type to initialize data members of the class type. The initial values of built-in or composite members depend on the scope of the object: in the local scope, these members are not initialized, but they are initialized to 0 in the global scope.
Ppps: Sometimes you need to construct the function initialization list. If no initialization type is provided for class members, the compiler implicitly uses the default constructor of the member type. If the class does not have a default constructor, the compiler will fail to use the default constructor. In this case, Initialization is required to initialize data members. Some members must be initialized in the constructor initialization list. For such members, assigning values to them in the constructor body does not work.No default constructorAndConstOr reference typeIn the constructor initialization list.
For example:
ClassConstRef {
Public:
ConstRef (int ii );
Private:
Int I;
Const int ci;
Int & ri;
};
ConstRef: ConstRef (intii)
{I = ii; // OK
Ci = ii; // error: cannot assign to a const, which can only be initialized
Ri = I; // assigns to ri which was not bound to an object, errpr
}
Changed to: ConstRef (int ii): I (ii), ci (I), ri (ii ){}
Ps: the sequence of member Initialization
Each member is in the constructor initialization list.Only onceThis is not surprising. After all, what does it mean to give a member two initial values? Perhaps even more surprising is that the constructor initialization list only specifies the values used to initialize members, and does not specify the sequence of initialization execution.The order in which members are initialized is the order in which they are defined.The first member is first initialized, then the second member, and so on. The initialization order is often irrelevant.However, if a member is initialized based on other members, the order of member Initialization is crucial.
For example:
Class X {
Int I;
Int j;
Public:
// Run-time error: I is initialized before j
X (int val): j (val), I (j ){}
};
In this case, the constructor initialization list seems to use val to initialize j and then use j to initialize I. However, I is first initialized. However, the actual effect of this initialization list is to use the j value that has not been initialized to initialize I!
If the order in which data members are listed in the constructor initialization list is different from that declared by members, some compilers are very friendly and give a warning. It is a good idea to compile the constructor initialization list in the same order as the member declaration. In addition, do not use members to initialize other members.
Written as X (int val): I (val), j (val) {} may be better!
L The initialization formula can be any expression, Sales_item (conststd: string & book, int cnt, double price): isbn (book), units_sold (cnt), revenue (cnt * price) {}
L class data member initialization,Any constructor of this type can be used.. For example, the Sales_item class can use any string constructor to initialize isbn. You can also use the limit value of the ISBN value to represent the default value of isbn, rather than an empty string. The isbn can be initialized to a string consisting of 10 9:
Sales_item ():Isbn (10, '9 '), Units_sold (0), revenue (0.0 ){}
L constructors can also have default parameters
L default constructor
The compiler automatically generates a default constructor only when no constructor is defined for a class. Even if only one constructor is defined, the compiler will not automatically generate the default constructor. The default constructor for merging uses the same rule as the variable initialization to initialize members. That is, class members use the default constructor, and built-in variables are not initialized (different from java, in java, values are initialized, that is, class members are null, int is 0, double is 0.0 ).
Ps: a default constructor should be defined for the class. If no constructor exists, the following problems may occur:
1. parameters must be passed when an object is defined.
2. This class cannot be used as an element type for dynamically allocating arrays.
3. If the container saves this type of object, such as vector, you cannot use constructors that only accept the container size.
Pps: use the default constructor
Sales_item myobj; // correct!
Or Sales_item myobj = Sales_item (); // first create an unknown object and then copy it to myobj
Sales_item myobj (); // used as a function declaration !!
Ø implicit class type conversion
ClassSales_item {
Public:
Sales_item (const std: string & book =): isbn (book), units_sold (0), revenue (0.0 ){}
Sales_item (std: istream & is );
};
When string null_book = 9-999-99999-9;
Item. same_isbn (null_book );
And item. same_isbn (cin); both implicitly execute the constructor to create a temporary object, and then call the function same_isbn.
But as follows:
ClassSales_item {
Public:
Explicit Sales_item (const std: string & book =): isbn (book), units_sold (0), revenue (0.0 ){}
Explicit Sales_item (std: istream & is );
};
The explicit keyword can only be used in the constructor declaration within the class. You cannot write the definition made outside the definition body of the class !!
Item. same_isbn (null_book); // error: string constructor is explicit
Item. same_isbn (cin); // error: istream constructor is explicit
Only item. same_isbn (Sales_item (null_book ));
Ps: Normally, unless you want to define implicit conversions for obvious reasons, the single-parameter Constructor (Conversion constructor ??) It should be explicit. Setting the constructor to explicit can avoid errors. When the conversion is available, you can explicitly construct the object.
Ø when all Data members of the class are public, Data val2 = {1024, Anna Livia Plurabelle} can be used };
In this way, the list order is defined by the member variables.
Ø youyuan
The membership mechanism allows a class to grant access to its non-public members to a specified function or class. The statement of youyuan starts with the keyword "friend.It can only appear within the class definition.. A friend statement can appear anywhere in the class: A friend is not a member of the class that grants a friend relationship, so they are not affected by Access Control in part of the statement. Generally, it is a good idea to put a friend declaration in groups at the beginning or end of the class definition.
Ps: type name of typedef in the public class. Class Name: type name is used for out-of-class access, such as vector : Iterator
Example:
ClassScreen {
Friend class Window_Mgr; // you can directly reference the private member of Screen in all the member functions of Window_Mgr.
};
Ps: youyuan can be a common non-member function, a member function of another class defined earlier, or the entire class. Set a class to youyuan. All member functions of the youyuan class can access non-public members of the class authorized to the youyuan relationship.
ClassScreen {
FriendWindow_Mgr & Window_Mgr: relocate (Window_Mgr: index, Window_Mgr: index, Screen &); // member function
};
Ps: When we declare a member function as a friend, the function name must be limited by the class name to which the function belongs.
2. youyuan declaration and scope
In order to correctly construct the class, you need to pay attention to the mutual dependency between the definition of youyuan and youyuan. In the previous example, the class Window_Mgr must be defined first. Otherwise, the Screen class cannot specify a Window_Mgr function as a friend. However, the relocate function can be defined only after the Screen class is defined-after all, it is set as a member of the Screen class for the category class.
Ø static class members
The class can define shared static data members, and the class can also define static member functions.The static member function does not have this parameter. It can directly access the static member of the class, but cannot directly use non-static members.
Ps: You can directly call static members from a class through the scope operator, or indirectly call static members through objects, references, or pointers to objects of this type. For example:
ClassAccount {
Public:
Void applyint () {amount + = amount * interestRate ;}
Static double rate () {return interestRate ;}
Static void rate (double); // sets a new rate
Private:
Std: string owner;
Double amount;
Static double interestRate;
Static double initRate ();
};
Accountac1;
Account * ac2 = & ac1;
Rate = ac1.rate (); // through an Account object or reference
Rate = ac2-> rate (); // through a pointer to anAccount object
Rate = Account: rate (); // directly from the class using th1_operator
Ps: when we define static members outside the class, we do not need to specify static reserved words repeatedly. This reserved word only appears in the Declaration within the class definition body, the same as explicit.
Pps: Because the static member is not part of any object, the static member function cannot be declared as const. After all, declaring a member function as const is an object that promises not to modify the call to this function, while a static member function is essentially a class name change (that is, an object call is used !). Finally, static member functions cannot be declared as virtual functions (not rewritten !!).
Ppps: static data members must be defined externally (exactly once) in the class definition body ). Unlike common data members, static members are not initialized through class constructor, but should be initialized during definition.
Double Account: interestRate = initRate ();
Similar to the static member function, the static keyword can only be used in the Declaration within the class definition body. The definition cannot be marked as static.
2. Special integer const static members can be initialized in the class definition body.
ClassAccount {
Public:
Static double rate () {return interestRate ;}
Static void rate (double); // sets a new rate
Private:
Static const int period = 30; // interest postedevery 30 days
Double daily_tbl [period]; // OK: period is constant expression
};
Constint Account: period; // No static, no initial value
Ps: When a const static data member is initialized in the class definition body, the data member must still be defined outside the class definition body. When the class provides initialization, the member definition does not need to specify the initial value, as shown in the preceding figure.