C Expert Programming: A comprehensive review of C + + (10)

Source: Internet
Author: User
Tags class definition

If you think C + + is not complex enough, do you know what protected abstract virtual base pur Virtual Private destructor inheritance mean? When was the last time you used it?
-----Tom cargill,c++ Journal Fall 1990
C + + may be more successful in software reusability than in previous languages. Because the inherited style of C + + is based on the object, which allows the inheritance of the data, it also allows the inheritance of the code.
Before 1985, C + + 's name was "C with classes", but now people have added very many features, from the point of view class, "C with classes" is a fairly reasonable extension of C language, it is easy to understand and explain. Immediately, people in this language has invested a great enthusiasm, has not yet attenuated. C + + is now a fairly large language. Specifically, the front-end of a C compiler has about 40000 lines of code, and a C + + compiler's front-end code might be twice times more or more.
This section is mainly for the C + + language features and some of the concepts summarized, originally did not intend to write, because the specific details of my [C + + PP (Edit 6)] also has a specific explanation, probably most of the repetition, but in order to summarize and review, review the C + + The difference between language and C language and some new features and related concepts, decide or write down, master skipped.
Object-oriented programming is characterized by encapsulation, inheritance, and polymorphism (dynamic binding). C + + supports inheritance through the derivation of the class and supports dynamic binding through virtual functions. Virtual functions provide a way to encapsulate the implementation details of a class system.
First, a comprehensive understanding of C + + concept and attention to the points of knowledge:
(1) abstract (abstruct):
It is a process of removing unimportant details from objects, and only those keys that describe the intrinsic characteristics of those objects are preserved. Abstraction is a design activity, and other concepts provide abstract oop (object-oriented paradigm) features.
The concept of abstraction is to observe a group of things and realize that they have a common theme. You can ignore the unimportant differences and only record the key data that can represent the characteristics of the thing. When you do this, it is an abstraction, and the stored data type is "abstract data type". Abstraction sounds like a difficult mathematical concept, but don't be fooled by it-it's just a simplification of things.
In software, abstraction is very useful, which allows programmers to achieve the following goals:
(1) Hide irrelevant details and focus on essential features.
(2) to provide a "black box interface" to the outside world, the interface determines the set of valid operations applied to the object, but it does not prompt how the object implements them internally.
(3) The decomposition of a complex system into several independent components. This allows for a clear division of labor and avoids the interaction between components that do not conform to rules.
(4) Reuse and code sharing.
Abstract an abstract data type is created, and C + + uses this feature of class l to implement it.
(2) class:is the user-defined type plus the operation on that type.
A class is a user-defined type, as if it were a built-in type such as Int. Built-in types already have a well-established set of operations for it, such as arithmetic operations, and the class mechanism must also allow the programmer to prescribe the operations that the class he defines can do. Anything inside a class is called a member of a class.an empty class has: constructors, destructors, copy constructors, assignment operators operator= four member functions. The following will be described separately.
The class mechanism of C + + realizes the encapsulation requirement of OOP, and the class is the software implementation of encapsulation. Classes are also a type, like char,int,double and struct st*. So you have to declare the variables of the class before you use it., like a class and a type, you can do a lot of things with it, such as getting its size or declaring its variables. objects, like variables, can perform many operations on it, such as getting its address, passing it as a parameter, returning it as a function, making it a constant value, and so on.
(3) objects (object):a specific variable of a class, just like J may be a variable of type int. An object can also be called an instance of a class (instance).
(4) package (encapsulation):combine types, data, and functions together to form a class. In the C language, the header file is an example of a very fragile package. It is a trivial encapsulation example because its combination form is purely lexical, and the compiler does not know that the header file is a semantic unit.
(5) Single Inheritance (ingheritance):This is a big concept-allowing classes to receive data structures and functions from a simpler base class.derived classes get the data and operations of the base class and can overwrite them as needed, or add new data and function members to the derived class. There is no concept of inheritance in the C language, and nothing can emulate this feature. When a class inherits or customizes the data structure and member functions of its unique base class, it becomes a single inheritance. Do not confuse an inheritance with another class nested inside a class. Nesting simply embeds one class inside another class,called inner class。
(6) Multiple inheritance:Multiple inheritance allows two classes to be combined into one class, so that the result class object behaves like one of the two classes of objects.
(7) virtual inheritance:The main solution is the problem of ambiguous access in multiple inheritance. All subclasses in virtual inheritance point to the same data space.
(8) Virtual base class:The parent class of virtual inheritance is called the virtual base class, which indicates that accumulation is shared by multiple, multi-inheritance classes. (generally avoid virtual inheritance when programming)
(9) Inner class (Inner):The relationship of the inner class to the outer class: compiler-related,VC6.0 They are two completely different classes, cannot use each other's things, if you want to use, can be defined as friend class; VS2005 compiler, inner class can use external class things, external classes cannot use inner class things.
The order in which the constructor of the inner class is run: The constructor of the outer class is called first, and if there is a parent class, the constructor of the parent class is called first. Then call your own constructor.
(10) purely virtual functions (pure virtual function): pure virtual function is a special virtual function, in many cases, the base class can not give a meaningful implementation of the virtual function, and declare it as pure virtual function, its implementation is left to the base class derived classes to do. This is the function of pure virtual functions (similar to interfaces in Java). Classes that contain pure virtual functions are called Abstract class(Contains at least one pure virtual function), it cannot generate an object.
Class father{public    :    virtual void Show () =0;//pure virtual function;}
(11) Template:This feature supports parameterized types.is a generic technique that implements variable algorithms with immutable code.
#include <iostream>using namespace Std;template<typename t>//function template cannot give default value; t Min (t a,t b) {   return a>b? B:a;} Template<typename t,typename r>void Show (T a,r b) {   cout<< "a:" <<a<< "B:" <<b<< Endl;} void Show1 (T c)//A function template cannot be used by more than one function; {   cout<<c<<endl;  Error, not knowing;}template<typename t,typename r=int>//only class templates can give default values; class Father{public  :     T A;     R b;}; Template<typename t,typename s>class Son:public father<s>//after the parent class with a <S> representation subclass with S to initialize the parent class; {//Initialize;}; int main () {    cout<<min (34,2) <<endl;    Show (at "Kongyin");    System ("pause");    return 0;}
(12) inline function (inline):Instead of generating a function call, the programmer can dictate that a particular function is expanded as a stream of instructions in the line (just like a macro), rather than producing an invocation of the function, which improves the execution efficiency of the procedure.
(13) exception Handling (Exception):The exception is automatically switched to the part of the code that the program uses to process the error code when an error occurs. The C standard library provides two special functions: setjmp () and longjmp (), which are the basis of structured exceptions, using the attributes of both functions to implement exceptions. The main role of setjmp and longjmp is to restore errors, I've talked about it in detail earlier.。 As long as you have not returned from the function, once you find an unrecoverable error, you can transfer the control to the main input loop and start again from there.
try{} cathch{} exception handling is unique to C + +. Examples are as follows:
#include <iostream>using namespace std;void show (int num) {    switch (num)    {case      1:        cout<< " Throw: ";        Throw num;      Case 2:        cout<< "throw:";        Throw "ERROR";}    } int main () {    try    {      Show (1);    }    catch (int a)//what type of throw is to be received by what type.    {     cout<< "catch:" <<a<<endl;    }    catch (char *str)    {     cout<< "catch:" <<str<<endl;    }    System ("pause");    return 0;}
(14) friend function (friend):a function that belongs to friend does not belong to a member function of a class, but can access the private and protected members of a class like a member function. FThe riend can be a function, or it can be a class.
(15) member functions (member function):The member function of an object that invokes a class is equivalent to the term "send a message to an object" used by an object-oriented programming language.Each member has a this pointer parameter, which is implicitly assigned to the function, which allows the object to reference the object itself within the member function。 Note that inside the member function, you should find that the this pointer does not appear, which is what the language itself involves.
#include <iostream>using namespace Std;class father{   private:     int number;   Public:     void Show ()     {       cout<< ' this address: ' <<this<<endl;     }}; int main () {   father ff;   cout<< "object's address:" <<&ff<<endl;   Ff.show ();   System ("pause");   return 0;}
Operation Result:


(16) constructor (Constructor): Most classes have at least one constructor. When an object of a class is created, the constructor is called implicitly, and it is responsible for initializing the object . Constructors are necessary because the class usually contains some structure, and the second structure contains many fields. This requires a complex initialization. When an object of a class is created, the constructor is called automatically.

(17) Copy constructor (copy Constructor): The copy constructor is also a special constructor, the name of the function is consistent with the class name, and its only parameter is a reference to this type. A, when using an object of an initialized custom type to initialize another newly constructed object, B, when the parameter of the function is the object of the class, and C, the return value of the function is the object of the class, the copy constructor is called.

(18) deep copy and shallow copy (bit copy): Simple understanding: deep copy, copying of objects, copying of resources; Shallow copy is just a copy of pointers, no replication of resources.

(19) destructor (Desconstructor):The class also has a cleanup function, called a destructor, that corresponds to the constructor function.The destructor is called automatically when the object is destroyed (beyond its lifecycle or when a delete operation is made to reclaim the heap memory it uses). A destructor is used as an insurance method to ensure that the synchronization lock is always released when the object leaves the appropriate range. So they not only know the object, but also clean up the locks held by the object. Constructors and destructors are necessary because any function outside of the class cannot access the private members of the class. Therefore, you need a privileged function inside the class to create an object and initialize it.However, both constructors and destructors violate the principle of "all work is responsible" in C language. They can make a lot of work in the program run by the implicit call to complete some functions, ease the burden of the programmer, this also violates the C language philosophy, that is, any part of the language should not be implemented by the hidden runtime program.
(20) Heavy Duty (overload):is simply to reuse an existing name, but to make it operate on a different type. Can be the name of a function, or it can be an operator.The return value of the function, the number of parameters, the type and the order can be different。 Overloads cannot be private, cannot reduce access rights, or are not overloaded. Overloads are parsed in the compiler.
(21) rewrite (overwrite):The function has the same name, parameter, and return value.The return types that are limited to parent-child are different. Polymorphism is implemented on the basis of rewriting.
(22) Polymorphism (polymorphism):Derived from Greek, meaning "multiple shapes".depending on the ability of different types to invoke different functions, a pointer to the parent class can point to the member function of the subclass, allowing the object to be bound at run time with the appropriate member function, and the runtime to select the correct member function based on the type of object. Also known as Shong Compile and lag compilation (late binding). How many subclasses the base class has, and how many forms the parent pointer has. Mainly through virtual functions, the key word is virtual. It is used to inform the compiler that a member function of the derived class may supersede a function of the same name as the base class.
 the principle is that a single inheritance typically implements a virtual function by including a vptr pointer within each object. The vptr pointer points to a vector of function pointers called VTBL (called virtual function tables, also known as v tables). Each class has such a vector, and each virtual function in the class has a record in the vector. With this method, all objects of the class share the implementation code. Implemented by this virtual table. is a generic type of technology. The first address of the virtual table is the first address of the object.
(23) virtual function (virtual):it cannot be declared as a virtual function: A normal function, a static member function of a class, an inline function, a friend function (not a member function of a class, C + + does not support), and a constructor. The conditions that can be declared as virtual functions are: (1) can be inherited; (2) The member functions of the class
(24) static member function:static member functions are part of a class, but are not part of any object, all objects share one copy, there is no need to bind dynamically,Also cannot be inherited "effect can, but mechanism cannot." A static member function is a copy of the entity, in the parent class, and the subclass inherits the parent class without copying the static function of the parent class, but the subclass can use the static member function of the parent class.and static member functions can only access static variables.
() New and delete operators:Used to replace the free and malloc functions. These two operators are more convenient to use.If the computational work of sizeof can be completed automatically, and the appropriate constructors and destructors can be called. New can really create an object,Then malloc simply allocates memory.
(26) Reference invocation (call-by-reference):Equivalent to a call to the address, the C language uses only the value call (Call-by-value). C + + introduces a reference call in the language, which can be passed as a parameter to the object's reference.
Second, C C language Improvement
(1) Type conversion can be written in a form like float (i) that looks more pleasing to the eye, or as a slightly weird C-style form like (float) i.
(2) C + + allows a constant integer to define the size of the array;
const int size =128;char str[size];
This is allowed in C + +, but is not allowed in C.
(3) Declarations can be interspersed between statements. In the C language, all declarations in a block of statements must precede all statements. C + + removes this arbitrary restriction, and the declaration can appear anywhere the statement can appear.
Although C + + is very complex, it is the only successful transformation program for C, with a large group of supporters.
three, C + + small knowledge points collection(See money for "C + + Programming Tutorial (Revision)") < knowledge points may have duplicates >
1.class in the default case of the member is private;struct default is public, struct can not have member functions;
2.:: Called the scope delimiter. When a party member function is implemented outside the class, it must precede the prefix "::", as if it were shouting loudly, "Hi, I'm important, I mean something belongs to this class",
Indicates which class A function and member belongs to. :: Can not be followed by the class name, representing the global function, that is, non-member functions;
3. The member functions defined in the class are inline inline functions, so that they are not copied at the time of the call, but that the pointer directly points to the entry address of the function, which increases the efficiency of the call;
4. The general size of the member functions is relatively small, so the switch statement is not allowed;
5. Function declarations are generally in the header file, and the definition of the function can no longer be the header file, because they will be compiled multiple times; using #pragma once means to call only once;
The 6.inline function must be visible to the compiler so that it can expand the function within the point of the call. Unlike a non-inline function, the inline function is not a jump for a function,
It is the deployment of instructions (thus improving execution efficiency). If the inline function is too large, it will cause the target code to be too large, increase the additional page break behavior, and reduce the hit rate of the instruction cache device.
So the compiler will automatically become non-inline;
7. Since the member functions in the class are inline inline, the problem of not being included in the early header file is avoided;
8. Because the class name is part of a member function, the member function of one class cannot be considered overloaded with the same names as another member function;
9. The space occupied by the object of the class is determined by the spatial synthesis occupied by his data members, and the member functions of the class do not occupy the space of the object;
10. The objects of the class have global objects, local objects, static objects and heap objects--pointer objects;
11. Constructors are member functions of a class, can have any number of arguments, can be overloaded, so can be placed outside the class definition, no return type, of course, there is no return value, but there can be no value return statement returns;
No object can be created without a constructor;
12. Destructor is also a special class member function, it has no return type, no parameters, can not be overloaded, the end of the object life cycle, the system automatically call;
13. Definition and declaration of objects and functions in a class:
Class Tdate{}tdate Day (); This is a normal function that declares a day, returns the Tday class object, Tdate day (int), creates a function, Tdate Day (10), and creates an object;
14. The destructor for the class will automatically call the destructor for each data member with a destructor;
15. The definition of a class is unallocated space and initialization;
16. A class is an abstract concept, not an entity, and does not contain attribute values, but only objects occupy a certain amount of space and contain explicit attribute values.
17. After the constructor, the colon represents the call to the constructor of the data member of the class, and the colon syntax is the initialization of the constant data member and the application data member, because the constant cannot be assigned, and the reference variable is not reassigned, and its value is fixed after initialization.
Class Student{public:   student (int &i): ten (Ten), refi (i) {}   protected:   const int ten;//constant data member;   int &refi;  Reference data member;   student ()   {    ten=10;  Error: Constants cannot be assigned;    refi=i;  Error: reference cannot be reassigned;}   }
18. If the data member of a class is a general variable, the same as the weight initialization of the function placed after the colon;
19. The only way to create an object is to call the constructor;
20. Local and static objects are objects that refer to block scopes and file scopes;
static objects are constructed only once: the static objects of the file scope are all constructed before the main function starts running. A block-scoped static object, which is constructed when the function defining the static object is first entered;
Class Student{public:  int n;  Student (int m_n)  {    cout<< "construct student" <<m_n<<endl;   }}   VOID fn (int m)  {    static student St (m);  local static constructors;    cout<< "fn:" <<m<<endl;  } int main () {    fn (ten);   FN (20);}
Operation Result:
construct student 10;//The constructor executes only once;
Fn:10;
fn:20;
21: The initialization and construction order of member variables and member objects is constructed in the order in which they are declared in the class, not in the order following the colon of the constructor function;
22. Object-oriented programming is based on two principles: abstraction and classification;---structured programming; comparison of efficiency:
A person physical strength is very good: he can ride through the streets and alleys to reach the destination, efficiency is relatively high, but if the two places far away, then it is not so easy, it is necessary to choose the train, aircraft, as long as pay to sit up on it, do not consider the middle process, this is the face object;
23. The efficiency of the operation of the program refers to the minimum amount of resources "storage space" and run relatively fast, can not one-sided look at a certain aspect, to synthesize a comparison of time and space objective evaluation of the efficiency of a program operation;
24. Global Data area: Global variables, static data, constants;
Code area: the member function and non-member code of the class;
Stack area: The local variables, function parameters, return data, return address for the function assignment;
Heap area: The remaining space is placed in the heap area;
reasons to need new and delete in class 25:
Because malloc cannot call constructors when allocating space, the creation of Class objects is a trinity of allocation space, construction structure, and initialization, which is done by the constructor, whereas malloc simply obtains a class object space containing random data, and the value in the corresponding object space is indeterminate. It must be initialized after the memory allocation, which is fundamentally not the creation of the class object, which bypasses the constructor;
The pointer object calls the destructor only when the delete is called, and if it is a local object, the destructor is called automatically when the local object exits the scope with a "concluding sentence} or a return" .
26. When allocating an array of objects, the type can be followed only by the [number of elements] and cannot be followed by the constructor's arguments, so allocating an array of objects from the heap can only call the default constructor, cannot invoke the other, and cannot be assigned to redeem the array if the class does not have a default constructor;
Student St[4];student *st[4];
Delete []Qty where [] is to tell C + + This is an array, fill in the numbers, the compiler will ignore, but if you do not write, it will produce errors;
27. The default function of an empty class: constructor, copy constructor, destructor, operator overloaded function, operator overload function operator=;
28. Instance object, pointer object "Heap object", temporary object, nameless object
Class student{     int numnber;} STUDNET fn () {  studnet ms (+);  return MS;} Student St (100);//Instance Object studnet *st =new studnet (100);//Pointer object Student (100);//Nameless Object studnet &sts=fn ();//Very dangerous, no longer valid;
29, typical three usages of nameless objects: Notice the difference between initializing the reference and initializing the object, and the difference between assignment and initialization;
VOID fn (studnet &s); int main () {    student &refs=studnet ("Jenny");  Initializes the reference; inside the function, the nameless object is generated in the stack space as a local object;  studnet Refs=jenny;     Student S=student ("Jenny");//Initialize the object definition, use a nameless object to copy the construction of an object s;studnet S=jenny; Omit the step of creating a nameless object; C + + calls the constructor "Studnet (char *) first; Create a Nameless object, and then call a copy constructor Studnet (student &) to create the object s; But since the unknown object is used to copy the construction, the Nameless object loses its meaning after the thing, so the step of creating the Nameless object is omitted;   fn ( Studnet ("Jenny")); function arguments; The Nameless object is passed to the parameter s as an argument, the constructor is called to create a nameless object, and then the Nameless object is initialized to the reference parameter S object, and the argument is in the main function, so the Nameless object is created in the stack area of the main function, the function fn () The formal parameter s refers to an object in the main function stack;  student S ("Jenny");  FN (s);}
30. Because the C + + default constructor is only a shallow copy of the object, if the object's data members include pointers to space (heap space), it cannot be used in this way, you must define the copy construction for its allocation space, that is, deep copy, the copy of the resource;






C Expert Programming: A comprehensive review of C + + (10)

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.