Basic knowledge of C + + (i)

Source: Internet
Author: User
Tags function definition shallow copy throw exception types of functions

First of all, C + + in the header file on the class of two curly braces to add a semicolon, or there will be a lot of strange strange errors .

One, each C + + program (or a C + + project consisting of multiple source files) must contain and have only one main () function. Standard C + + still supports this format for pre-processing directives such as # include <iostream.h> header files with C language style. But it can also be used in C + + style: #include <iostream>, but in order for the definition in iostream to be valid for a program, a namespace compilation directive is also required: using namespace std; //Don't forget the semicolon . using is the instruction that is processed before code is compiled. Namespace is a namespace that is a new feature of standard C + + that resolves a potential crisis in a program with the same name identifier (such as a function with the same name) .

/*...*/is used for multiline comments,//For single-line comments. Each preprocessing command (macro definition, file inclusion, conditional compilation) must occupy a single line, and no semicolon at the tail, must start with # (#define, #include, #ifde F. #else: #endif, #if. #elif: #endif).

The exit () and Abort () functions are commonly used in C + + to terminate program execution, exit(0) indicates normal exit program; exit (not 0 value) indicates an exception exit .

Four, try and catch, throw usage

(1) Basic introduction

the function of the TRY statement block is to start the exception handling mechanism, which can cause an exception when the program statement executing the TRY statement block is detected . Throws an exception if there is an exception (you can also throw an exception directly with the throw).

The Catch statement block is used to catch exceptions that are generated by the TRY statement block, including exceptions thrown with throw, and then processed . A try always appears with a catch, and after a try statement block, there should be at least one catch statement block. A catch statement block must precede a try statement or another catch block. When the entire parameter in a catch is "...", the catch can catch any type of exception.

try{...

throw value; Actively throwing exceptions in the program

}catch (parameter type [parameter name])//Pass the exception value to the parameter and use the parameter in the CATCH block

{    ...

Exception Handling Statements

}

Throw throws an exception value, catch accepts (incoming parameter), and the throw must be in a try statement block .

(2) in-depth throw:

(i) After the program accepts the throw statement, the destructor is automatically called, the domain (inside the in-try parentheses) object is clean up, and then into the catch statement (if you exit the loop in the loop body). This mechanism can cause some fatal errors, such as when a "class" has a pointer member variable (again a pointer!). ), the exit caused by the throw statement in the class builder causes the object pointed to by this pointer to be non-destructor. Here very basic, do not go deep, hint, the pointer to the class on the line, such as template class to replace the pointer, set a destructor inside the template class.

(ii) Statement "throw;" Throws an exception that cannot be caught, even if it is a catch (...) Can not be captured, then enter the termination function

(3) in-depth catch: The general catch appears in the form of

Try

{...

}catch (EXCEPT1 &)

{...

}catch (Except2 &)

{...

}catch (...) Accept All exceptions

{...

}

generally written as references (except1&), the reason is simple, efficient .

throw an exception, but what if the catch is not an exception? (Note that no Java-like finally statement) invokes the default termination function when a catch does not catch a matching exception. You can call Set_terminate () to set the terminating function, which is a function pointer with the type: void (*terminate) ().

What if there is no try-catch to throw in the program directly? Cause the program to terminate

(4) Try a function body, the form is as follows

void Fun (Type1,type2) try//try after the function body

{

function definition

}catch (Type X)

{...}

The effect of this usage is equivalent to:

void Fun ()

{

try{function Definition}

}

(5) Throw a function body, the form is as follows:

void Fun (); Can throw any type of exception

void Fun () throw (EXCEPT1,EXCEPT2,EXCEPT3)

{...} Inside the parentheses is an exception parameter table, this example can only throw in the 3 exception

void Fun () throw () {}//Parameter table is empty, cannot throw exception

What happens if a fun () throws an exception that is not in the exception parameter table?

Answer: Call the terminating function set in Set_terminate (). However, this is only a superficial phenomenon, in effect invoking the default unexpected () function, but this default unexpected () calls the terminating function set in Set_terminate (). The unexpected can be set with set_unexpected (), just like set_terminate (), but after the new "unexpected ()" is set, the terminating function set in Set_terminater is no longer called. This syntax is very useful, because in the use of other people's code, do not know which place will call what function and throw what exception, with an exception parameter table in the declaration of limitations, very practical.

(6) throw does not necessarily appear in the TRY statement block, it can appear wherever needed, even in the catch block, you can still continue to use throw, as long as there is a catch can catch the exception it throws . When the throw appears in a catch block, the throw can either re-throw a new type of exception, or it can be re-thrown (at this point, the throw should not take any arguments).

Try

{   ...

}catch (int)

{

Throw "Hello exception";//throws a new exception with the exception type const char*

}catch (float)

{

Throw Re-throws the current float type exception

}

V. for public members of the class, they are publicly available and can be accessed outside the class;

For protected members, they are semi-protected and have a semi-public nature that can be accessed in a class or subclass;

for privated members, they are private and cannot be accessed outside the class, and data members and function members are called only when defined by other function members of this class ( objects cannot access private members ).

It is important to note that if the declaration and definition of a member function is done in the class body at the same time, the member function does not need to be defined separately, and the function defined in the class body is quite an inline (incline) function defined outside the class. If all member functions are defined in the class body, the member function definitions outside the class can be omitted. when the definition of a member function for a class is done outside the body of the class, you must use the scope operator:: To tell the compiler which class the function belongs to. Members of this class are accessed in the same way as struct access members, and objects can only access public members in the class and cannot be accessed for protected members and private members .

Vi. class constructors, destructors, assignment functions

(1) Constructor: When the class object is created, the compilation system allocates memory space for the object and automatically calls the constructor, which is done by the constructor to complete the initialization of the member . constructor function: Initializes the data member of the object, and the constructor's function name is the same as the class name. Constructors generally have the following types of functions:

No parameter constructor:example (). If you create a class and you do not write any constructors, the default parameterless constructor is automatically generated, the function is empty, and nothing is done. As long as you write a certain constructor, the system will no longer automatically generate such a default constructor, if you want to have such a parameterless constructor, you need to write it yourself.

General constructors (also called overloaded constructors):example (Arg1,arg2 ...). General constructors can have a variety of parameter forms, a class can have more than one general constructor, if the number of parameters or different types (based on the principle of overloaded functions of C + +). Different constructors are called depending on the parameters passed in when the object is created.

Copy constructors (also known as copy constructors):Example (const example &C). The parameters of the copy constructor are references to other objects of this class, which are used to copy a new object of the class based on an existing object, typically copying the value of the data member of an existing object into the newly created object in the function. If there is no write-copy constructor displayed, the system creates a copy constructor by default, but when there are pointer members in the class, there is a risk that the copy constructor is created by default, for specific reasons, such as "Shallow copy" and "Deep copy". the default copy constructor created by the system only performs a "shallow copy", assigning the value one by one of the data member of the copied object to the newly created object, if the data member of the class has a pointer member, Will cause the new object's pointer member to point to the same address as the pointer member of the copied object, and delete the pointer causes two repetitions of the delete error. At this point, you should define the copy constructor yourself , and in the copy constructor, use new as a pointer member of the newly created object to re-open a piece of memory, and then use the strcpy function to copy the content pointed to by the pointer member of the copied object into the new memory. The pointer member of the newly created object that points to the new memory address will no longer point to the same address as the pointer member of the original object.

Example (const example & c)

{
Copies the value of the data member in Object C so that the private member of Object C can be accessed directly in the function.
M_real =c.m_real;
M_img =c.m_img;
}

Type conversion constructor:example (double c). Creates an object of this class based on an object of a specified type. A example object is created in front of an object of type double.

void Main ()

{
Call the parameterless constructor, the initial value of the data member is assigned to 0.0
Example C1,C2;

Call General constructor, data member initial value is assigned
Example C3 (1.0,2.5);
Example C3 = Example (1.0,2.5); Another form

Assigns the value of the C3 data member to C1
Since C1 has been created beforehand, no constructors are called and only the = operator overload function is called (Assignment function)
C1 = C3;
Invoking a type conversion constructor
The system first invokes the type conversion constructor, creates 5.2 as a temporary object of this class, and then calls the Equals operator overload to assign the temporary object to C1
C2 = 5.2;

Call copy constructor (there are two ways to call)
Example c5 (C2);
Example C4 = c2; //Note and = operator overloading is distinguished, where the object to the left of the equals sign is not created beforehand, so the copy constructor needs to be called and the parameter is C2

}

(2) Assignment function:example&operator= (const example &RHS). Note that this is analogous to the copy constructor, which copies the value of the object of the right-hand side to the object on the left side of the equal sign, which is not a constructor, and the object on both sides of the equal sign must have been created . If the Write = operator overload is not displayed, the system also creates a default = operator overload, which only does some basic copy work.

Example &operator= (const EXAMPLW &RHS)

{
First detect whether the right side of the equal sign is the object of the left, if the object itself, the direct return
if (this = = &AMP;RHS)
{
return *this;
}
Copy the member to the right of the equal sign to the left object
This->m_real =rhs.m_real;
This->m_imag =rhs.m_imag;

Send the object to the left of the equal sign again
The purpose is to support even eg:a=b=c, the system first runs B=c
Then run a= (the return value of B=c, which should be the B object after the C value is copied)
return *this;
}
(3) destructor:~example ()。if no destructor is defined, the compiler automatically generates。 The effect is to release the memory that an object occupies (called when the object is being deleted).A typical application of this is to open up independent dynamic memory space in a constructor with new for pointer-type members in a class, and to release them in destructors with delete。 Destructors are just a function, no different from normal functions, and what you want it to do is just what you have to tell him. Therefore, the destructor can also be an empty function, only in a reasonable time to release their allocated memory, such as new must delete, malloc must be free, as for you where you want, do not have to be in the destruction of the inside, and placing it in a destructor can cause memory that you don't want to use until the program runs (the destructor is called only when the object is deleted).

Vii. about function & Test () {return value;} The & in front of the function name, which represents a reference to the function returned. The reference return is used when you want to use a function to find out which variable the reference should be bound to. Define a variable A to call a = &test (), which indicates that the address of variable A is the same as the address of the return value. The change in the value of the variable A is caused by the test () return value. if value is an array name, it is written as function * Test () {return value;}

The so-called & refers to the alias of a variable, followed by the name of the variable it is referencing. A reference is just an alias, not a type, but only the address of the data it refers to, so it differs from the pointer character *. The reference does not have an address in memory and does not occupy space, and once initialized it cannot be modified, so there is no pointer to the reference. That is, the reference is equivalent to a constant pointer, the address pointed to is fixed (but the contents of the point to the address can be changed), and no longer use this reference pointer to another address.

The reference is actually pointing to something, so in this sense it is a "pointer", but he is definitely not alone, he must be indicating something that already exists, he must be an "alias" of an already existing object. and if it is initialized and assigned to a variable, he is always the alias of the variable. A change to a reference is a change to that variable.

For example, int &a=b; A is the address of B, then B can be regarded as the alias of variable A, because it is to assign a reference to variable B.

Basic knowledge of C + + (i)

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.