Chapter IV C ++ Primer Plus

This article is the study notes, have their own understanding, if there is wrong place, please correct me

4.1 Array

In C ++ array is a data format that can store multiple values ​​of the same type, such as int, float, short

Array declarations should be noted that the following three points:

1. array of worth in each element type

2. Array name

3. The number of elements in the array

Here with python python is not the same place is very casual, C ++ requires additional element declarations and type of the value of the number of elements

For chestnut:

short months[12];
/* 通用格式: typeName arrayName[arratSize] */

The general format of the top Obviously it

Note that the compiler does not check the use of the array index is valid, if an assignment to an element that does not exist, the compiler does not complain (cattle batch), but the program is running may lead to error, this must be a valid index value (Remember this ah, do data array 10, to a subject beyond the assignment, of course, like Python like its assignment rules, months [0] = 1 this)

4.1.2 array initialization

int months[3]={1,2,3};

C ++ allows the array initialization statement, enclosed in braces, on the map as,

rule:

1. Only when it can define an array initialization

2. Initialize the array to provide the time value may be less than the number of elements in the array, of course, does not provide the remaining element values, all initialized to O, of course, is a fast initialization method below zero, only to provide a position array subscript 0 0

int months[3]={0};

3. If the initialize an array, square brackets ([]) do not specify the number of array elements, to the number of elements calculated by the compiler, and the example below, the compiler automatically calculated, the array comprising four elements

int months[]={1,2,3,4};

Note that this is very bad, very bad, because if offers less value, then the number will be less calculated values ​​in the array, this will result in deviation, do you think the four values, but forgot one array containing three, have hidden follow-up

C ++ 11 new features

You can omit the "="

int months[2]{1,2,3};

Braces do not contain anything on behalf of all initialized to 0

int months[3]{};

4.2 String

There are usually two strings

char dog[3]={"b","a","k","l"};
char dog[3]={"bakl"};

I think with the first frenzied, and first encountered space character will stop, and the second no problem

4.2.1 stitching string constants

cout <<"i like" "you.\n";
cout <<"i like you. \n";
cout <<"i"
"like you.\n;

The top three of these can not increase the mosaic character, mosaic character behind the front will be followed by character

4.2.4 read a line of the input string

cin.getline(name,10)

This function is to read the entire line, then no more than nine characters, automatically increasing the null character at the end, reading the specified number of characters or line breaks to stop reading, but not a newline saving, storing string back when the space character to replace newline

cin.get()

The first similar getling (), but no longer read and discard newline, but added to the input queue, if two calls to get (), the second call to see the character is a newline, so it will stop, so you can use the following method of

cin.get(name,AirSize);
cin.get();
cin.get(name,AirSize);

There would also be

cin.get(name,AirSize).get();

Blank lines and other questions:

getline () or get () reads a blank line, what will happen next input will be blocked, can be restored by cin.clear ()

If the hybrid input, it can only be called splicing

(cin >> year).get(); // or (cin >> year).get(ch);

4.3 String class

This is also a method of treatment string, String Class located std namespace may be initialized to be the input cin, cout can be displayed by an array of objects may be displayed string representation

The difference is that a simple statement is a character array of variables, operators can also use the "+" to splice

Other operations 4.3.3 string class

strcpy(charr1,charr2); // copy charr2 to charr1

strcat(charr1,charr2); // append charr2 to charr1

Of course, the length of the character may be calculated,

Array class:

int len1 = strlen(charr1);

Use string can use this:

int len1 = str1.size()

4.4 Structure

Array can store the same data, such as 20 Int, so there was structure to meet user demands for more data storage, use the keyword struct show

struct inflatable
{
    char name[20];
    float volume;
    double price
};

This can be stored in different data (python seemingly random array can store .....)

Then you can declare a variable of this structure

inflatbale pao = 
{
    "Glorious Gloria",
    1.88,
    29.9
};

It's a bit like the object-oriented. . . . Pao.name output data is output is "Glorious Gloria"

Then that is a problem () declared inside and outside the main, with variables, their own brain supplement

4.4.6 union

union one4all
{
    int int_val;
    long long_val;
    double double_val;
};

This is actually a common body structure may not store a plurality of data types, can only store one, sometimes int, sometimes long, sometimes double, two or more items, they can save space, typically used to save memory, because the union is anonymous. Therefore address two members would like to use, without intermediate identifier id_val, the programmer is responsible for what is active

4.6 Enumeration

enum spectrum{red,orange,green};

Is to increase the mandatory provisions of the assignment, the assignment may not exceed

If you do not create an enumeration type variable, you can omit the name of an enumeration type

Enumeration variables can be output directly, but can not be directly input. Such as: cout >> color3; // illegal
can not be directly assigned enumeration constants. Such as: color1 = 1; // illegal
between different types of enumeration can not be assigned to each other. Such as: color1 = color3; // illegal
input and output variables of the enumeration switch statement is generally used to convert a character or character string; other types of data processing enumerated switch statement often applied to ensure the legitimacy of the program and readability.
4.7 Pointers and free storage space

First talk about three basic properties of the computer program stored in the data must be tracked

1. Where information is stored

2. How much value is stored

3. Storage of information is what type

Value of the address pointer is stored, can address operator (&), such as a value of Home, & home so that his address

The name is a pointer address, operators are called an indirect value or dereferencing operator, to a value of this address can be stored, if the name is a pointer, then the name is represented by a value stored in the address

4.7.1 declare and initialize the pointer

int * p1, p2 want to emphasize this, this statement represents a pointer and an int variable, each pointer variable name, you need a *

It follows a simple initialization address pointer

int higgens = 5

int * pt =  &higgens

note:

long * fellow;
* fellow = 2332233;

On top of this there is no address assigned to this fellow would not know where to put 2,332,233,

long fellow = 2332233;

long * fe = &fellow;

Warning: therefore, must be applied before the pointer dereferencing operator (*), the determination of a pointer is initialized, the appropriate address, which is used for the golden rule pointer.

4.7.4 use new to allocate memory

int * pn = new int;

new operator to determine how many bytes of memory required according to the type, and the return address to find the memory

The general format is as follows:

typeName * pointer_name = new typeName;
int nights = 1001;
int * pt = new int;
*pt = 1001;
double * pd = new double;
*pd = 10000001.0;

But know, new assigned value storage memory allocated from the heap or free store memory, variable memory area in the stack

4.7.5 release memory using the delete

To use the new use of memory, of course, you can delete to free memory

int * ps = new int;
...
delete ps;

As is the release of the ps memory

But memory can not be released already freed memory blocks, as well as declaring variables obtained

as follows:

int * ps = new int;
delete ps;
delete ps; // not ok now
int jugs = 5;
int * pi = &jugs;
delete pi; // not allow, memory not allocated by new

4.7.6 use new to create a dynamic array

int * pt = new int [10];
delete [] pt

But * pt is a pointer to the first element of the array value

But you can still be used pt [1], pt [0] value such access array

The use of new, delete comply with the rules:

1. Do not use delete to free allocated memory is not new

2. Do not use delete to free the same memory block twice

3. If using new [] array to allocate memory, you should use delete [] to release

4. If a new entity to allocate memory, use delete (without brackets) to release

5. For a null pointer is safe to delete applications

4.8.4 use new to create a dynamic structure

inflatable * ps = new inflatable;
this period can not be used know the address of the operator, the operator to use the arrow (->)

If the structure is a configuration identifier name, operator use periods, if the structure is a pointer, using the arrow operator

An array of alternatives 4.10

The array write about it

array<typeName, n_lem> arr;

array<double, 4> a3 = {3.14, 2.72, 1.62, 1.41};

to sum up:

Arrays, structures, and pointers are three types of compound, the array may store a plurality of values ​​of the same type in a C ++ object data, and by using the indexing subscript of each element of the array can be accessed

Structure can be many different types of values ​​are stored in a single data object, you can use the membership operator (.) To access the members of which, using the structure of the first step is to create a template structure that defines the structure of the memory of those members , will become the new name of the template type of identifier, then you can declare a variable of this type of structure

Union may store a value, but the value may be of different types, it indicates the member name mode of use

Bai pointer is designed to store the address of a variable, we say that it is a pointer to the memory address, pointer type statement that the pointer to the object, a pointer operator reference contact applications, the resulting value of the position of the pointer

Ending null character string is a series of characters, a string constant string can be enclosed in quotes, where implicitly contains null character, may be in the char array can be initialized with a string stored represents a string, the string functions strlen char pointer to point () returns the length of the string, excluding the null character, function strpy () to copy the string from one location to another, when using these functions, it should be and it includes the header file string.h csting

Supported header string C ++ string class provides a good alternative for the user character string processing method, the object string will automatically adjust its size to be stored in the character string, the user may use the assignment operator to copy the string

new operator request to allow memory data objects when the program is running, the operator returns the memory address obtained, this address may be assigned to a pointer, the program will only use the pointer to access this memory, if the data object is a simple variable can be used in contact with a reference operator (*) to obtain the value, if the data object is an array, it is possible that the use of pointers as using the array name to access elements, if the data object is a structure, it is possible to use the pointer dereferencing operator (->) to access its members

Pointers and arrays are closely related, if the name is an array ar, ar expression [I] is interpreted as * (ar + i), wherein the array name is interpreted as the first address of the array element, so that the role, and the array name the same pointer, in turn, can use the array notation, an array of new access pointer name assigned by the elements

New and delete operators allow the display control when the memory allocated to the data objects, when the memory is returned to the memory pool, automatically declared variables are variables in the function, and the static variable is outside the function or variable declared with the static keyword , the two variables are less flexible, automatic variables generated when program execution to block it belongs (usually a function definition), while leaving the termination block, the static variables are present throughout the program cycle, C + +98 new standard template library STL provides a template class vetor, it is a substitute for dynamic arrays, C ++ 11 provides a template class array, it is a fixed-length array of alternatives

Pointer Summary:

1. Declare pointer

To declare a pointer to a specific type, please use the following format:

typeName * pointerName;

// Here is an example

double * pn;

char * pc;

// where, pn and pc are pointers, and double * char * is a pointer to double and a pointer to a char
2. Give pointer assignment

Should be assigned to the memory address pointer, it can be applied to the variable name & operator to obtain the memory address of the named, new new operator returns the memory address of the unnamed

Here are some examples

double * pn;

double * pa;

double * pc;

double bubble = 3.2;

pn = &bubble;

pc = new char;

pa = new double[30];
  1. Dereference the pointer

Means for obtaining a pointer dereferences pointer value, pointer dereferences and indirect application value operator ( ) to dereference, therefore, if, as in the example above, bubble point pn is a pointer, then the pn value is directed , or 3.2

Here is an example:

cout << *pn
*pc = "s";

Another method is to use a pointer dereferences array notation, e.g., pn [0] * pn is the same, not to a non-initialized for the proper address pointer dereferencing

4 identifies the value of the pointer and the pointer points

If pt is a pointer to int, then * pt is not a pointer to an int, but exactly the same as a variable of type int, pt is a pointer,

Here is an example:

int * pt = new int;
*pt = 5;
  1. Array name

In most cases, C ++ an array name as the address of the first element of the array

Here is an example

int tacos[10];

An exception is the sizeof operator for an array name, then return the entire array length (in bytes)

  1. Pointer arithmetic

C ++ allows pointers and integers are added, the result is equal to 1 plus the value of the original address plus the total number of bytes occupied by the pointing object, but also a pointer to another value may be subtracted to obtain a difference between the two pointers, the latter the resulting integer arithmetic, only when two pointers to (a position beyond the end point may be) of the same array, this operation makes sense, that the resulting separation of the two elements

The following is an example of

int tacos[10] = {5,2,8,4,1,2,2,4,6,8};
int * pt = tacos;      // suppose pf and tacos are the address 3000
pt = pt + 1;           // now pt is 3004 if a int is 4 bytes
int *pe = &tacos[9];   //pe is 3036 if an int is 4 bytes
pe = pe -1;            //now pe is 3032, the address of tacos[8]
int diff = pe - pt;    // diff is 7, the separation between
                       //tacos[8] and tacos[1]

Guess you like

Origin blog.csdn.net/u013693952/article/details/90726888