C + + Advanced Object-oriented Foundation (III)

Source: Internet
Author: User
Tags class definition shallow copy

 definition of class : initialization is generally recommended to use constructors to initialize the list form: Person (Const stringNmConst stringaddr): Name (NM), address (addr) {}this pointer: Use this pin  in a class, especially if some of the cases cannot be omitted, such as calling a member variable of a parent class in a method of a subclass, plus this, Otherwise, some compilers do not pass, and for exampleclassper{Per&GetName () {return* This; } Per&Getage () {return* This; }}; This is called per per; Per.getname (). Getage (); If the function is also const, then the corresponding return should also be const and, can be based on const function overloading; object creation, if you are creating a pointer, you must use new. Constructors: Reference types, const types, members of class types that do not have a default constructor, must be initialized in the list again. friends , Friends: You can directly adjust the private members of the yuan. Friend function A declares in class B that Class A becomes a friend class of Class B, declaring Class A in class B. Example: Class a{friendclassb ;}; "Means B is a friend of a class, then B can use anything of a". The private member of a can be called arbitrarily in class B. Static member: A member of a shared public, such as a class, that declares two objects, which are public and exclusive to the static members of the two objects . Ordinary members, however, do not have this characteristic. Therefore, it can serve as a global variable between classes, and the advantage of all variables is that it avoids the disturbance of global variables between different classes, and is suitable for the encapsulation of global variables of a certain class of data. static variables can be initialized directly to static variables through the scope operator of the class , or use, Class a{Static floatx;} a::x =0.3; In addition, static member functions cannot use this pointer because static member functions do not belong to any one object, because they are public , such as static const integer variables, which can be initialized directly when declared in class. None of the rest is possible . copy constructor, assignment operator ; The above two, if you do not write, C++one is written by default. Many times you don't have to write your own, but when a member of a class is a pointer, be sure to write one yourself . The copy constructor has only one parameter and is generally the current class of the const type, for exampleclassa{a{ConstA &a): X{a.x},y (A.Y) {}} The copy constructor will copy the members of the current object into another object. So can A (b); Assignment operators: When a data member of a class has pointers, it is generally necessary to write an assignment constructor when the memory is allocated dynamically. class a{a& operation = (const A &b) {a.x = b.x; a.y = B.y;}}; So you can direct A =b;b copy constructor:classa{ Public: A (a& B): P (NewSTD::string(* (B.P))) {}// If the default copy constructor is dropped, this is a (a& b): P (B.P) {} Just copies the pointer to the pointer, and our goal is to get the original string and use it to initialize the current pointer and recreate a string . Private: str::string*p;} The same value assignment operator is: A& Operation= (Const&b) {P=NewSTD::string;// If the default is only P = b.p, and does not use the number inside the real copy. Shallow re -system*p = *(B.P); return* This;} destructor: If you write a destructor, you should write the copy constructor and copy the operator. (Three Laws) shallow copy with deep copy the data member is a pointer, be sure to do a deep copy. If the class operates the system resources, as long as the dynamic allocation of resources, replication, also must write deep copy . Management pointers: (When a class has pointer members, be sure to note) Regular pointer classes (shallow copy) to avoid shallow copying, generally the following methods: Smart pointer Class (count Class) has a shallow copy of the characteristics, data sharing, but does not produce a wild pointer Value type (deep copy) each member in the Smart pointer class is private, with a pointer inside and a corresponding counter variable. Overloaded operators: Keywordsoperatoroperator overloading: input and output operator overloading, especially input operator overloading, should be careful to check the input. Arithmetic operator overloading,+ General Non-member function, + =generally as a member function. Operator Overloading: (conversion operator)operator int()Const. Must be a member function, cannot specify a return value, the formal parameter list must be empty and must be displayed to return a value of a specified type, usually defined as a const type, to prevent changes to the converted object. classa{ Public: A (): X (3){}    operator int()Const{        returnx;}Private:    intx;} A;inty = A;//This allows a class type to be automatically converted to an int type and then copied to Y. base and derived classes: Members of protected and public, which can be used directly in subclasses, but not in subclasses, to obtain corresponding protected members through the base class. Protected members can not be called directly from the base class, and therefore protected members, the base class is available directly, and can only be used internally within the base class definition, and can no longer be used directly from other places. class Base{ Public:    intx;protected:    inty;Private:    intZ;}classBundle_base: Public Base{ Public: Bundle_base ():Base(){}    voiddisplay () {cout<< x<< Endl;//you can call X directlycout << y << Endl;//can be called directly    }    voidDisplay (Bundle_base &a,Base&b) {cout<<a.x<<Endl; cout<<a.y<<endl;//and this protected member Y, in other scopes is not directly called, in the subclass of the region, it is equivalent to become a private member. ?? cout <<b.y <<endl;//It 's not going to work here.}} Virtual function: Can be overridden and not overridden, pure virtual functions: must be overridden. Dynamic binding (polymorphic) polymorphism, a transformation of a derived class to a base class, a reference or pointer to a base class object, or a derived class object, which is dynamically bound only when a virtual function is called by reference or pointer. Three kinds of inheritance are generally inherited with public, almost without protected and private inheritance, the default is private inheritance, Java only public inheritance. In private inheritance, to change the type in the public of the base class back to public, you can modify the inherited access by using the private attribute of the individual member. classa{ Public:    intx; inty;}classD |Privatea{ Public:usinga::x;//This turns x into a common inheritance.Y//the y here, for B, is the private member, because it is a proprietary inheritance. Distinguish the above (modify inherited access) mode. the constructors and destructors of derived classes derive from the constructors of the inheriting classes, constructors, Binate call the constructors of the base class, and invoke the constructor of the member object, and finally call its own constructor. Note: This process occurs when you construct the destructor class. classC | PublicB PublicA Publicc{//when constructing E, the constructor is called in the order of B,a,c,d,e. The reverse order of destructionPrivate: D D;} Conversions and Inheritance: reference conversions/pointer-to-object conversions (derived classes to base classes) pass derived classes to the base class, and if the object is passed, polymorphism cannot be implemented. 1,void(Base a) {a.function ();}2,void(Base &a) {a.function ();}3,void(Base *a) {a->function ();}; If a subclass is passed to base class base, then if the object is passed 1, the function using the base class cannot be used to achieve the meaning of polymorphism, so it is generally used with 2 and 3, reference and pointer passing. If you are converting a base class to a subclass, one is forbidden, and if you want to do so, you need to cast. Friends and inheritance: Friends can access the private and protected members of the class. But there is a meta-relationship that cannot be inherited. Static members and inheritance: static members in the base class, with only one instance in the entire inheritance hierarchy. Access method: Base class Name:: member name Subclass Name:: Member name object. Member name Pointer-member name Member name (in subclass, as long as there is access) pure virtual functions and abstract classes: Classes that contain pure virtual functions are abstract classes, and pure virtual functions are followed by virtual function declarations plus"=0;", the definition of pure virtual function can write not write, generally do not write, let subclasses to implement; Abstract classes cannot create objects, i.e. they cannot be instantiated, only inherit; pure virtual functions must be implemented; Abstract classes with pure virtual functions become C++interface. A subclass of a class with pure virtual functions, the corresponding function must also be a virtual function, so the corresponding destructor is also a virtual function, but the corresponding subclass is not an abstract class, you can instantiate its object. (because destructors for classes with virtual functions must be virtual functions) templates and generic programming: Class templates and Function templates; Template programming is also called generic programming. Queues: Sequential queue push pops front Rear isempty and so on, sequential queue is a queue made with arrays, midway new space. If the size changes, you have to reassign the space. Queues: Chained queues use lists of queues that are more flexible and simpler to design than sequential queues. Function templates: function Templates-a function, the instantiation. Using the template parameter Templates <typename t>code reuse can generally be implemented. Exception:Try Catch ThrowException Type: number, String, class object. For example, the error is not return this way, but with Thow to throw an exception. Exceptions can be thrown with numeric objects and strings. intIsxequal () {if(x==y) Thow2;} Or thow "failed", etc. to run out of the exception. The call can be made with tyr{isxequal ();}Catch(inte) {printf ("Exception%d\n",1); When an exception occurs, it runs the Catch section, which is much better than the return to check what the error result is. Catch(...) {printf ("exeption\n");} Catch all exceptions with ' ... ' instead. Exception (2): Create your own exception class in the class to create the exception class, the class name is generally used in the form of XName (x First name), when used, directly throw xName; classarray{Private: size_t itssize; Public: Array (size_t x): Itssize (x) {}classxbase{ Public:Virtual voidPrinterror () {printf ("The exeption comes\n");} }    classXName: Publicxbase{Virtual voidPrinterror () {printf ("The exeption name comes\n");} };//If you need to write more than one exception class and return multiple different exceptions, you can use a polymorphic method, inherit a class, and then use the virtual function in the base class to get the exception of the base class    classXsize: Publicxbase{Virtual voidPrinterror () {printf ("The exeption size comes\n");} }    voidGetSize () {if(size>3)Throwxsize (); if(Itssize <1)ThrowXName (); }}; When called, you can:Try{array arr (3); GetSize ();}Catch(Array::xbase &exep) {//Be sure to pass by reference or pointer, polymorphic technology, you can use a catch to catch all the exceptionsexep.printerror ();}Catch(Array::xname) {//Of course, you can use an exception on a single basis, preferably using the method aboveprintf"name exeption\n");} Exception: Standard exception exception Runtime_error rang_error overflow_error underflow_error logic_error domain_error invalid_argument Length_error Out_of_range Bad_alloc (exception with excessive allocation of space)Try{    intx =New int[100000000000];}Catch(Bad_alloc err) {printf ("Bad alloc err\n");} function pointer: Smart pointer is a pointer template class. Often resolved: deep copy, copy on write, reference count, reference connection, destructive replication. Std::auto_ptr boost function pointer, smart pointer in the ATL framework. Commonly used shared_ptr,unique_ptr,weak_ptr. Smart pointer classes have a clear explicit constructor, so when using smart pointers, it requires explicit conversions that do not allow ambiguous conversions, as smart pointers are used, just like pointers. shared_ptr<Double>PD;Double*p_reg =New Double;PD= shared_ptr<Double>(P_reg); or shared_ptr<Double>pshared (P_reg); Note the following ambiguous conversions are not allowed: for example, PD= P_reg; shared_ptr<Double> pshared =P_reg; Also note that you cannot use the Shared_ptr,auto_ptr and Unique_ptr namespaces when allocating memory without new: Each namespace is a scope, the namespace can be disjoint, the interface and the implementation are detached, and nested namespaces. (Namespaces can prevent duplicate names) in the header file without using Std::cout, and so on, generally where to call, directly use std::cout inside, because this will bring a lot of things into the header file. Aliases for namespaces: for example,using namespacec =Std::cout; As an alias, you can reduce the length of the namespace. Multiple inheritance and virtual base class: (It is recommended not to use multiple inheritance, or to minimize the use of multiple inheritance, generally using single inheritance) Many languages have canceled multiple inheritance, but multiple inheritance is C++one of the most important features. Multi-inheritance is separated by "," between multiple parent classes. In multiple inheritance, note the sequence of calls to constructors and destructors. In particular, the initialization list of constructors is to be aware of the initialization of the constructor list of the parent class. For example, a constructor: Subclass (intx): Y (x), BaseClass (2x), Base1class (x, 2x) {} The problem of ambiguity is very important: a parent Class A has two subclasses b,c, and then these two subclasses b,c are the parent class of another class D. So when building D, B will be constructed, then B will call a construct once, and the C construct will also construct a once, so that it will construct a two times, resulting in two semantics, that is, two a objects. In general, the virtual base class is used to solve the two semantic problem: the use of virtual inheritance, here is the B and C virtual inheritance a. ThatclassD |Virtual  Publica{B () {A ();//virtual base class must recall the parent class's constituent function} A () {}}classC:Virtual  Publica{C () {A ();//virtual base class must recall the parent class's constituent function}}, then d normally inherits B and CclassD: PublicB Publicc{}, then, when you construct D, B, and C are constructed, but when you construct B and C, you do not construct a.  Only the D construct, once constructed a, will not produce two A. Special tools and Technologies:extern"C": Allocator class: Commonly used for memory that is not allocated to fixed size. such as allocator<aClass> A; A.allocate ( -); For the AClass class, a space of 100 size is allocated. Rtti technology: such as dynamic_cast dynamic type conversion, at runtime to identify the technology, you can turn the base class into a subclass, that can be converted downward. If the subclass is assigned to a base class, it can be done automatically (automatically when the conversion is up). Rtti technology, such as typeID (AClass). Name () can get the class name of AClass. Pointer to a class member: A pointer to a member of the class, such as std:: iten_base: :*PF = &ITEN_BASE.ISBN; Pointer pf that points to the member of the Iten_base IsBn.  You can also define a pointer to a member function of a class. Union utest{CharCV;intIntv;DoubleDV;}; If Utest ut= {'a'}; cout << Ut.intv <<Endl, the output will be 97, that is, the CV assic code value, because the inside is common, that is, all the same value. Bit field: A bit used by a member of a class, such asclassxc{Bit V:1; Bit B:2;}volatile(easy variable identifier):volatile intY Tell C + + not to optimize him, because this variable may be unstable.

C + + Advanced Object-oriented Foundation (III)

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.