Note 3-class initialization assignment and analysis structure

Source: Internet
Author: User
Class 1 initialization most classes provide a special default constructor which does not need to specify the initial value. In typical cases, if the class object is initialized by the default constructor, we can consider it not initialized yet. Class A {public: Int; Int B ;}; Class A does not require constructors because all its data members are public. Int main (){ A test = {0, 1}; // correct. These values are resolved by location according to the Order stated by data members. Getchar (); Return 0;} display two main disadvantages of the initialization table: A can only be applied to objects of all data members that are public classes. B needs Program The constructor 1 displayed by the Member cannot specify the return type, in addition, the parameter names in the constructor 3 declaration can be declared in a class with the same name as the class. Account (const char *, double = 0.0); 4. Specify the real parameters for the constructor. There are three equivalent forms of account acct1 ("Anna press "); account acct2 = Account ("Anna press"); account acct3 = "Anna press "; // It can only be used for single parameter 5. Only when no constructor or the default constructor is declared can we not specify the real parameter set to define the dynamic array of Class Object 6 objects when allocating memory. requires or has a default constructor or no constructor. For example, if you write this code, the newly defined account class will fail. // error: the default constructor account * pact = new account [new_client_cnt] is required. class 7 initialization list class initialization there is a replaceable syntax member initialization table member initialization list is a list of member names separated by commas and their initial values. For example, the default account constructor can write // use the default account constructor inline account of the member initialization table:: Account (): _ name (0), _ balance (0.0), _ acct_nmbr (0 ){ } The member initialization table can only be specified in the constructor definition rather than in its declaration. The initialization table is placed between the parameter table and the constructor body starting with a colon. 8 constructors cannot be declared using the const or volatile keyword. The appropriate constructor applied to the class object is irrelevant to whether the object is const non-const or volatile. Only after the constructor is executed. When the class object has been initialized, the constant of the class object is created. Once the Destructor is called, the constant will disappear. Therefore, a const class object is considered a const class object during the period from its constructor completion to the destructor. The same applies to volatile class objects. 9 by default, the single parameter constructor or multiple parameters except the first parameter have default real parameters used as conversion operators. // In a header file, extern void print (const account & ACCT); // ...int main () {// converts "oops" into an account object // use account :: account ("oops", 0.0) print ("oops ");//...} 10 The explicit modifier notifies the compiler not to provide implicit conversion class account {public: explicit account (const char *, double = 0.0 );//...}; explicit can only be applied to constructors. 11 The default constructor is a constructor that can be called without the need to specify real parameters. This does not mean that the constructor cannot accept real parameters. It only means that every parameter of the constructor is used. there is a default value associated with it. For example, each of the following functions represents a default constructor // each is a default constructor account:: Account (){...} Istack: istack (INT size = 0 ){...} complex: complex (double Re = 0.0, double im = 0.0 ){...} when we write int main () {account Acct ;//...} the compiler first checks whether the account class defines the default constructor. In one of the following cases, 1 defines the default constructor. It is applied to Acct. 2 defines the default constructor, but it is not public. The definition of Acct is marked as a compilation time error: Main () has no access permission. 3. No default constructor is defined, but one or more constructor that requires real parameters are defined. Definition of Acct is marked as compilation time error: Too few arguments 4 no default constructor defined or other constructor defined. This definition is legal. Acct is not initialized and no constructor is called. 12 if the account class declares all its members as public but does not declare the constructor, if a static object is declared as follows // static range // the memory of each object is initialized 0 account global_scope_acct; static account file_scope_acct; account Foo () {static account local_static_acct ;//...} ensure that the Members are initialized to 0 pairs of non-class objects. Self-Summary: If a does not define any constructor, members of the static object B will not be initialized to 0C. If the part of the object is initialized, uninitialized members are randomly assigned unknown. 13 The accessibility of the constructor is determined by the access zone in which the constructor declares it. You can place the constructor in a non-public access area to restrict or prohibit some form of object creation. The main use of non-public constructor is: A prevents the use of a Class Object to copy to another class object. B indicates that the constructor can be called only when a class is used as the base class in the inheritance hierarchy and cannot be directly manipulated by the application. 14. The copy constructor uses a class object to initialize another object of the class. It is called default by member initialization. In terms of concept, one class Object copies another class object by copying each non-static data member at a time. You can change the default behavior by providing a special copy constructor. Summary of member initialization: A can only display and define static members outside the class (except for const static) b. For const and referenced members, only three types of destructor can be initialized in the member initialization list. 1. A destructor is a special user-defined member function, when an object of the class leaves its domain, or the delete expression is applied to the pointer of an object of the class, the Destructor is automatically called. The Destructor name is to add the Tilde (~) to the class name (~), It does not return any value or any parameter, so it cannot be overloaded. 2. If the data members of a class are stored by value, no destructor is required. 3. The dynamically allocated object programmer uses the new expression to create dynamically allocated objects and the delete expression to end the life cycle of such objects. Dynamically assigned objects can be a single object or an array of objects. 4. dynamically allocate and release a single object. int * Pi = new Int. Feature 1: The assigned object has no name. Feature 2: The allocated memory is not initialized. Delete PI; release memory // is this necessary if (Pi! = 0) delete PI; no need, because the compiler will automatically detect after the delete expression, Pi is called a void pointer, that is, pointer to invalid memory. A better way is to set the pointer to 0 after the object pointed to by the pointer is released. The delete expression can only be used to direct to the memory. It is a pointer allocated from the idle storage area using the new expression. A fails to apply the delete expression to the common error of dynamic memory allocation. Memory leakage B applies two Delete expressions to the same memory area. This usually happens when two pointers point to the same dynamically allocated object. C. Read and Write the object after the object is released. 5 auto_ptrauto_ptr is a class template provided by the C ++ standard library. It can help programmers automatically manage a single object dynamically allocated using the new expression. # Include <memory> auto_ptr <type_pointed_to> identifier (identifier); auto_ptr <type_pointed_to> identifier (auto_ptr_of_same_type); auto_ptr <type_pointed_to> identifier; auto_ptr <int> Pi (New int (1024); auto_ptr <string> pstr_auto (new string ("brontosaurus"); auto_ptr <string> pstr_auto2 (pstr_auto ); // use pstr_auto to initialize pstr_auto2. Who is responsible for deleting the allocated memory? When pstr_auto is defined, it knows that it has ownership of the initialization string and has the responsibility to delete the string. When an auto_ptr object is initialized or assigned a value using another auto_ptr object, the objects assigned or initialized on the left have the ownership of the underlying objects in the free storage area, the auto_ptr object on the right revokes all responsibilities. Therefore, in our example, we will use pstr_auto2 to delete the string object, instead of pstr_auto, it will no longer be used to point to the string object. Similar behavior occurs on the Value assignment operator. The following two auto_ptr objects are known: auto_ptr <int> P1 (New int (1024); auto_ptr <int> P2 (New int (2048 )); the value assignment operator can copy an auto_ptr object to another object, as shown below: p1 = P2; after the object pointed to by P1 is deleted and assigned a value before the assignment, P1 has the ownership of the int type object. The object value is 2,048. P2 is no longer used to point to the object get () returns the underlying pointer of the auto_ptr object. If (p_auto_int.get ()! = 0) reset () function p_auto_int.reset (New int (1024); we cannot assign values to the address of the object created with the new expression after the auto_ptr object is defined: void example () {// default, use 0 to initialize auto_ptr <int> PI; {// Pi = new int (5) not supported );}} ///// to reset an auto_ptr object, we must use the reset () function. We can pass a pointer to reset (). If you do not want to set this auto_ptr object, you can pass in a 0 value. Auto_ptr <string> pstr_auto (new string ("brontosaurus"); // Delete the brontosauruspstr_auto.reset (new string ("Long-neck") object before resetting ")); in this case, use a string to operate assign () re-assigning values to the original string object is more effective than deleting the original character rate object and re-assigning the second string object. // In this case, the reset is more effective. // use the string assign () set the new value pstr_auto-> assign ("Long-neck"); we should note that a cannot be used to initialize and assign the value auto_ptr by pointing to "memory not allocated by applying the new expression. If this is done, the delete expression will be applied to memory that is not dynamically allocated. B cannot allow two auto_ptr objects to have ownership of the objects in the free storage zone. The release () operation allows you to initialize or assign the underlying object of an auto_ptr object to the second object without having two auto_ptr objects simultaneously have the same object ownership. Release () is not just like get () returns the address of the underlying object and releases the ownership of the object. Code Segment can be correctly rewritten as follows // OK: The two objects still point to the same object // However, pstr_auto no longer owns auto_ptr <string> pstr_auto2 (pstr_auto.release ()); 6. The new expression returns the pointer int * Pia = new int [1024] to the first element of the array. // you can specify an array containing 1024 elements, normally not initialized, the array allocated in the free storage area cannot provide the initialization value set. The built-in arrays created in the free storage area must be initialized in the for loop. That is, the elements of the array are initialized one by one: For (INT Index = 0; index <1024; ++ index) Pia [Index] = 0; char * str1 = new char [strlen (errortxt) + 1]; the expression calculated at runtime replaces the dimension with the two forms of a two-dimensional array: 1. A (* GA) [N] = new A [m] [N];... delete [] GA; disadvantage: N must be known. Advantage: intuitive calling, continuous storage, and concise Program (tested, the Destructor can be correctly called) 2. A ** GA = new A * [m]; for (INT I = 0; I <m; I ++) ga [I] = new A [n];... for (INT I = 0; I <m; I ++) Delete [] Ga [I]; Delete [] GA; disadvantages: non-continuous storage, cumbersome program. GA is a ** type. Advantages: intuitive calling, n can dynamically allocate and release const int * PCI = new const int (1024) instead of a known 7-constant object ); the const object must be initialized. the pointer that uses the value returned by the new expression as the initial value must be a const pointer of the carton type. You cannot create a new const array. A simple reason is that you cannot initialize the new array (except the class array ). 8. The displayed destructor calls char * arena = new char [sizeof image]; image * PTR = new (ARENA) image ("Quasimodo "). Instead, PTR is assigned the address associated with arena. With PTR, memory is interpreted as an image object. Remember, the compiler will call the Destructor only when the pointer in the delete expression points to a class type with destructor. The array of four types of objects and vector1 cannot provide an explicit set of values for initialization for the elements in the array of class objects allocated in the heap. If you want to support array allocation through the new expression, the class must provide a default constructor or not provide the constructor account * pact = new account [10]; an array of 10 account class objects allocated in the heap is created and initialized using the default constructor of the account class. Delete [] the initialization of the pact2 heap array requires two steps to initialize the Class Object array allocated in the heap by default: A actually allocates an array. If the default constructor is defined, then it is applied to each element, B, and each element is assigned a specific value. Vectorvector <point> VEC (5) of the three types of objects. The element initialization process is as follows: 1. Create a temporary object of the underlying class type and apply the default constructor of the class to it. 2. Apply the copy constructor to each element of the vector in sequence. Use the copy object of the temporary class object to initialize each class object. 3. delete a temporary class object. 5. What is the difference between using the initialization list and assigning values to data members in the constructor? The results of the two implementations of A are the same. The difference is that the member initialization table only provides the initialization of the data members of this type. In the constructor, setting the value of the data member is a value assignment operation. The importance of the difference depends on the category of data members. Constructor is divided into two stages: implicit or display initialization stage and general computing stage. The computing phase consists of all the statements in the constructor. In the computing phase, data member settings are considered as values rather than initialization. The display or implicit display in the initialization phase depends on whether a member initialization list exists. The default constructor of all base classes is called in the order declared in the implicit initialization phase. Then there is the default constructor for all member class objects. For class objects, the difference between initialization and assignment is huge. The member class object should always be initialized in the member initialization list. The const type and reference type must be initialized in the member initialization list. Parameters of other types do not matter. Because when the const body starts to execute, all const and referenced initialization must have occurred. Each member can only be initialized once in the member initialization table. The initialization sequence is not determined by the order of names in the initialization table, but by the order in which the members are declared in the class. The value is assigned by the Member. 1 // copy the value. the general form of the operator classname & classname:: Operator = (const classname & RHs) {// ensure that if (this! = & RHs) {// class copy semantics here} // return the assigned object return * This;} Here, the conditional test is if (this! = & RHs) should prevent a class object from assigning values to itself. Because it is not suitable for copying itself to release resources related to the object first, so as to allocate resources related to the object to be copied. 2. When a class object is assigned to another class object, such as newacct = oldacct, the following steps will happen: A checks the class, checks whether it provides a displayed copy assignment operator B. If yes, checks the access permission and determines whether it is available in this program. If it cannot be called, A compilation time error is generated. Otherwise, you can call it to perform the value assignment operation. D. If the class does not provide the displayed copy constructor, assign values by default. E by default, each data member of the built-in or composite type is assigned to the corresponding member. F recursion A to E for each class member object

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.