Reproduced from:
Http://www.cnblogs.com/kkdd-2013/p/5370094.html
C Set sail 1h 1 C Brief Introduction 2 Cide environment to build 3 C first experience 4 C language new features C new features C input and output cNAMESPACE 5 exercise C Departure 15h 1 Reference reference to reference type of struct body type For function Parameters 2 Const const and basic data type const and pointer type const and reference summary 3 function function parameter default value function overload inline function code Practice 4 memory Management 5 exercises C Package 2h 1 Class and object Introduction-dog example-TV 2 class object To define access code practices for instantiated object members of an object 3 string string type to initialize a string object common operation code practice string Practices 4 property encapsulates the benefits of encapsulation of data Code Practice 5 classes define the relationship within the class definition and the inline function Class definition Code Practice 5 Object Object Structure object initialization constructor constructor code practice default constructor constructor initialization list initialization list code practice copy constructor function destructor Code practice 6 Exercises C Package 3h 1 Object members to array object array object arrays Code practice object Member object Member code Practice 2 deep copy with shallow copy deep copy and shallow copy depth copy code Practice 3 object Pointer object Pointer object Pointer code practice object member pointer in memory member pointer code practice this pointer this pointer code practice 4 const Order 5 regular pointers and references to frequently referenced objects and regular references to object pointers and constant pointers 6 exercises
1.c++ Sail 1h 1.1 C + + Introduction 1.2 c++ide Environment build 1.3 C + + first experience 1.4 C + + language new features 1.4.1 C + + new features 1.4.2 C + + input 1.4.3 C + + Namespace 1.5 exercises
#include <stdlib.h> #include <iostream> usingnamespace std; * *************************************************/////////////////////////////// *////* Use a function to find the maximum and minimum value in the array////////* ****************************************
* * int getmaxormin (int *arr, intcount, boolismax) {int temp = arr[0];
for (int i = 1; I <count; i++) {if (Ismax) {if (temp <arr[i]) {
temp = Arr[i];
} else {if (temp >arr[i]) {temp = Arr[i];
}} return temp;
int main () {int arr1[4] = {3,2,5,8};
BOOL Ismax = false; Cin >> Ismax; Enter the CIN and output cout in the iostream header file, so include the header file at the beginning of the program, plus the namespace std cout << getmaxormin (arr1, 4, Ismax) << Endl
; System ("pause");//system in the stdlib.h header file, so at the beginning of the program the header fileIncluded in return 0; }
Let's think about a problem, if the getmaxormin () function is developed by a company, such as the company called Compa. If the company Compa want to publish this function and avoid a function with the same name as other companies, you need to add a clear space before your function name. When you add a namespace, you put your own functions into the namespace. When used, you need to add namespaces, the entire program is as follows:
#include <stdlib.h> #include <iostream> usingnamespace std;
namespace Compa {int getmaxormin (int *arr, intcount, boolismax) {int temp = arr[0];
for (int i = 1; I <count; i++) {if (Ismax) {if (temp <arr[i))
{temp = Arr[i]; } else {if (temp >arr[i]) {T
EMP = Arr[i];
}} return temp;
int main () {int arr1[4] = {3,2,5,8};
BOOL Ismax = false; Cin >> Ismax; Enter the CIN and output cout in the iostream header file, so include the header file at the beginning of the program, plus the namespace std cout << compa::getmaxormin (arr1, 4, Ismax) <& Lt
Endl
System ("Pause"),//system in the stdlib.h header file, so you want to include this header file in the beginning of the program return 0; }
The results show that we can use this method to distinguish between the same name of each company's functions, but in use, we need to precede the function with the appropriate namespace. 2. C + + departure from Port 1.5h 2.1 cited examples
As a child, there is a child in the yard, named Luo So-and-So, appearance, head large body small, so the other children in the yard to Luo So-and-so had a nickname (alias) called Turnip Head. In this way, life, Luo So-and-so is the real name of the child, radish head is this child's alias.
So, what do you mean by reference .... A reference is an alias.
computer, a reference is an alias for a variable.
thinking: can only alias, but no real name.
In life, if someone only has an alias, does it become his real name? Visible, only aliases, life is not feasible in fact, and in the computer, certainly the same reason, is not tenable. reference to the base data type
Take a look at the following code:
#include <iostream>
using namespace std;
int main ()
{
int a = 3;
Int&b = A; The reference must initialize
B = ten;
cout<< a <<endl;
return 0;
}
Code Interpretation:
We define a basic data type, which defines an integer variable A, give it an initial value of 3; then give the variable a an alias B (int&b = A;), it should be noted here, if only alias B, followed by all steps, at compile-time will be an error, so, when the alias, Be sure to indicate which variable is the alias, that is, the reference must be initialized.
We then assign a value of B 10, output the value of the variable A, we will see the output is 10. From the result of the program running, the modification of the alias is the modification of the actual variable . Like in life, we let the turnip head to work, is actually let Luo so-and-so to work is the same truth. reference to struct type
#include <iostream>
using namespace std;
Typedefstruct
{
int x;
int y;
} Coor;
int main ()
{
Coor C1;
Coor&c = C1; To C1 up the individual named C
c.x = ten;
C.Y =;
cout<< c1.x <<endl;
cout<< c1.y <<endl;
return 0;
}
Code Interpretation:
First, define a coordinate type of structural body coor, it contains the horizontal coordinates x and ordinate y, then defines a struct variable c1 in the main function, and then c1 the structure body with an alias, called C, and then assigns the coordinates x and ordinate y in C, respectively, The corresponding data member is manipulated by an alias, and finally, the horizontal and ordinate of the entity C1 are printed out through the output function. From the print result, the horizontal axis of the entity C1 is 10, and the ordinate is 20. ( because the action alias is no different from the action entity ) a reference to the pointer type
Reference to pointer type is defined by: type * *& *pointer alias * = * pointer ;
#include <iostream>
using namespace std;
int main ()
{
int a =10;
int *p = &a; Defines a pointer to the shaping variable a
int *&q = p;//gives the pointer p an alias q
*q =;
cout<< a <<endl;
return 0;
}
Code Interpretation:
In the program, first defines a shape variable A, and assigns an initial value of 10; Then a pointer variable p is defined, and the pointer p points to the shape variable A (int *p = &a;), and then we give the pointer p a name Q and a Q value of 20 (here's a copy of *p to 20, Since P is pointing to a, it is equivalent to assigning a a value of 20), and finally outputting a. From the output result, the value of a is changed to 20. reference as a function argument
To swap two numbers before you have a reference, you need to do the following
#include <iostream>
using namespace std;
void Fun (int *a, int *b)
{
int c=0;
c = *a;
*a =*b;
*b = C;
}
int main ()
{
int x=10, y=20;
Fun (&x, &y);
cout<< x << ', ' << y <<endl;
return 0;
}
From the above procedures, it is more cumbersome, but also requires a certain degree of understanding ability.
When we have a reference, the program can write this:
#include <iostream>
using namespace std;
void Fun (Int&a, int&b)
{
int c=0;
c = A;
a =b;
b = C;
}
int main ()
{
int x=10, y=20;
Fun (x, y);
cout<< x << ', ' << y <<endl;
return 0;
}
From the above procedure, the function is much simpler, the incoming two arguments will be alias A and b respectively, the exchange of aliases is equivalent to the actual operation of the entity. 2.2 Const const and basic data Types
First of all, without the Const keyword, we want to define an shaping variable, which is in memory as follows:
int a = 3; Variable
Variable name store address store content
A &a 3
When we add the keyword const to the variable name, it changes from a variable to a constant, as follows:
const int a = 3; Constant
At this point, if you reassign a value of 5 or another value, the computer will complain because at this point A is a constant and must not be changed.
Variable name store address store content
A &a 3 const with pointer type
Several defining ways and differences:
(1) const int *p = NULL;
(2) int const *P = NULL;
(3) int * Const P = NULL;
(4) const int * Const P = NULL;
(5) Int const * Const p = NULL;
Note: * (1) * and * (2) * Complete equivalence, * (4) * and * (5) * Complete Equivalence
Example:
int x = 3;
const int *P = &x;
At this point if p = &y; Correct, and if P = 5; Error ( because at this point **const* is decorated with *p)
int x = 3;
int *const p = &x;
At this point if p = &y; Error ( because at this point the ***const* is *p*, and *p* can only point to **x)
const int x = 3;
const int *const p = &x;
At this point if p = &y; *p = 5; are wrong (because you cannot modify the value of X at this time, and you cannot point p to other variables ) const and Reference
Example:
int x = 3;
const int &y = x;
x = 10; Correct (because x is a variable at this time and is variable)
y = 20; Error (because Y is an alias for X, preceded by a const modifier, immutable) summary
(1) const int x = 3; x = 5; x(because x is immutable at this time)
(2) int x = 3; const int y = x; y = 5; X(because Y is constant at this time and cannot be assignable)
(3) int x = 3; const int *y = &x; *y = 5; X(because the const modifier is *y at this time)
(4) int x = 3; z = 4; int *const y = &x; y = &z; X(because the const modifier is pointer y at this point, it points to immutable)
(5) const int x = 3; const int &y = x; y = 5; x(because x is a constant, Y is a reference to x, and y is a constant, you cannot reassign y).
(6) const int x = 3; int *y = &x; x(because x is a constant at this point, and pointer y is a variable, you cannot point the variable pointer to an immutable variable.) If you do this, the computer is risky, and the risk is that you can use *y to modify the value of X.
(7) int x = 3; const int *y = &x; √ 2.3 function function parameter default value
There are the following function declarations:
void Fun (int i, int j = ten, int k = 20); √
void Fun (int i, int j = ten, int k); X
Note: Parameters with default parameter values must be at the very right end of the parameter table
You can take a parameter default value when you declare a function, and when you define it, it is not recommended to take the default value of the parameter. If the function parameter defaults are also written when the function is defined, some compilers are able to compile through the actual compilation, and some compilers will not pass.
Example:
#include
#include function Overload
what is a function overload ...
In the same scope, multiple functions defined with the same function name , but the number of arguments or the type of argument between these multiple functions is called overloaded functions.
For example, define the following two functions (function: Take the maximum value)
int Getmax (int x, int y, int z)
{
To do;
}
Double Getmax (double x, double y)
{
To do;
}
As you can see from the top two functions, the function names are the same, but the number of arguments and the types of the arguments are different, so the two functions are overloaded functions.
thinking: How the compiler recognizes overloaded functions ...
When the actual compiler compiles, it is done as follows:
int Getmax (int x, int y, int z) gets getmax_int_int_int after compiling
Double Getmax (double x, double y) is compiled to get getmax_double_double
From the results of the above compilation, the form of a name *+* parameter is compiled to form a new function name to distinguish two overloaded functions, and in the process of invocation, the computer is automatically recognized by the type of arguments you pass in and the number of arguments automatically. To invoke the corresponding function.
Note: With respect to the function overload, this blog is more in-depth: Functions overloaded inline functions for C + +
The difference between an inline function and a normal function:
1, inline functions and ordinary functions in the definition of little difference
2, inline functions and ordinary functions in the invocation of the difference is as follows:
If you use the calling function to invoke a normal function, you will do the following 5 steps:
To call Fun ()-> find the relevant function entry of fun ()-> execute fun () related code-> return to the main function-> the main function and run other code until the end
If you use the calling function to invoke the inline function, the function body code and arguments are replaced by the function call statements at compile time, which in fact omits the above procedure (2) and (4), which saves a lot of time for the call, especially when the loop call is used.
inline function Keywords: ****inline
**inline **int Max (int A, int b, int c); Declare an inline function max
int main ()
{
int i =10, j =, k = m;
m = max (i,j,k);
cout<< "max =" << m < code practice
Complete the method that returns the maximum value using the overload of the function.
Now there is an array that defines a method Getmax (), using the overload of the function, to implement the following:
1, arbitrarily remove two elements in the array, to the method Getmax (), you can return a larger element.
2, the entire array to the method Getmax (), you can return the largest element in the array.
Complete executable program:
#include <iostream>
using namespace std;
/
* Function function: Returns the maximum value of a and B
*a and B is two integers
/int Getmax (int a, int b)
{return
a > b a:b;
}
* * Function function: Returns the maximum value in the array
* arr: integer array
* Count: Array length
* This function is the overload of the above
function
/int getmax (int *arr,int Count)
{
//define a variable and get the first element
int temp=arr[0] of the array;
for (int i = 1; i < count; i++)
{
//compare variables with the size of the next element if
(Temp<arr[i])
{
//If the elements in the array are larger than the Maxnum, Gets the value in the array
temp=arr[i];
}
return temp;
}
int main ()
{
//define int array and initialize
int numarr[3] = {3, 8, 6};
Automatically invoke Intgetmax (int a, int b)
Cout<<getmax (6,3) <<endl;
Automatically invokes the function that returns the largest value in the array returns the maximum value in the array
Cout<<getmax (numarr,3) <<endl;
return 0;
}
2.4 Memory Management
what is memory management.
Thinking: What is the nature of memory. --> Resources
Thinking: Who is in charge of memory resources. --> Operating System
Thinking: what we can do. --> application/Return
application */* Return of memory resources is memory management
How to apply and release memory in C + +.
request -> use operator new
free -> using operator Delete
namely:
application Memory: ****int *p = new int;
free Memory: * Delete p;*
This will request and release one memory or one type of memory
thinking: How to apply and release block memory.
int *arr = new INT[10]; 10 integral blocks of memory requested
delete []arr; Free Block Memory
think: Whether the application memory will be able to apply for success. Obviously, not necessarily.
Therefore, when encoding, it is necessary to process the possible request memory failure
int *p = new int[1000];
if (NULL = p)
{
Memory allocation failed
}
After freeing the memory, assign the corresponding pointer to null, that is,
Delete p; delete []p;
p = NULL; p = NULL;
If the freed pointer is not empty, the current pointer points to the corresponding block of memory, and if we accidentally call the delete again, the same memory is recycled, and the computer will get an exception once it is recycled.
Summary:
1 Use new to request memory, use Delete to free memory
2 The application of memory needs to determine whether the application is successful, the release of memory needs to be the pointer to empty
3 new and Delete to support the use of
Finally, look at an example:
Request 100 char types of memory in the heap, copy Hello Imooc string to memory in the allocated heap, print string, and finally free memory.
Complete executable program:
#include <string.h>
#include <iostream>
using namespace std;
int main (void)
{
char *str = new char[100];//Requests 100 char-type memory
strcpy (str, "Hello Imooc") in the heap;//copy Hello C + + String to memory in the allocated heap
cout<<str<<endl;//print string
delete []str;//free memory
str=null;
return 0;
}
2.5 Exercises
3. C + + package on 2h
3.1 Classes and Objects
Example ——-Dog
If we keep a dog, it has the following information:
information *-–* name: Wang Cai, age: 1 years old, breed: Big Dog
Skill *--* call, run
When we specifically refer to a thing, it is an object
But when we have more than one dog, in order to facilitate management, we will create a form
name |
Age |
Variety |
Big Strong |
1 |
Big |
Two strong |
2 |
Small |
Three Strong |
1 |
Big |
...... |
...... |
...... |
...... |
...... |
...... |
Common skills: Barking, running
Thus, the information of a group of dogs is abstracted so that a class can be defined.
Think about it: The abstract is not all the information about the dog.
Why not define such a message?
What is the protein content of dog meat?
What is the period of the dog's slaughter?
This is because, we are not concerned about eating, so this information is not used to us.
Conclusion: Different abstract information is different in purpose. Example ——-TV set
If there is a television, we can know its name and model by means of a name tag on the TV, we can control its volume through various knobs, and we can connect and cut off the power. Then we use the class to describe the following:
But there are still many implementation details that are not described in the class, which does not mean that it does not exist, but is hidden. For example: The working process of the circuit board. If these are all exposed to TV users, the people who watch TV will surely go mad. In fact, this is selective exposure.
The implementation details are encapsulated, exposing only the parts of the user's concern, which is called encapsulation.
If we list all the information about the TV set, you can always judge which information needs to be exposed and which information is not to be exposed.
But all this information is defined in the class, how to expose the information you want to expose and hide the information you want to hide.
To this problem, C + + provides us with a thing called an access qualifier .
Access qualifier:
Public: Common
Private: Personal
Protected: Protected
The information you want to expose is used for public decoration, and you want the hidden information to be decorated with private.
definition of Class 3.2 objects instantiation of an object
In C + +, a class is a template, and object instantiation is the process by which a computer creates multiple objects based on the design of a class.
The following defines a TV class that has two attributes or data members, one is the name of the TV, the other is the TV, and there are two other methods or member functions, one to adjust the volume and one to switch the power supply.
There are two ways of instantiating an object:
(1) instantiation from the stack
If we want to instantiate the class above and want to instantiate it from the stack, we can do this:
(2) Instantiation from heap
If we want to instantiate the class above and want to instantiate it from the heap, we can do this:
Note: The difference between two ways of instantiating
Instantiate the object from the stack, after use, do not need to ignore ourselves, the system will automatically release its memory footprint, and from the heap instantiation object, after use, we must release this memory.
thinking:
Through the stack or through the heap, we have instantiated the object, then have these objects even if it is over.
--The objects we instantiate are just a display.
Obviously, we are not so boring, we are going to visit the various members of these objects to achieve our goal. access to Object members
The generated object accesses its data members and member functions in different ways by instantiating the objects differently.
The stack instantiation object accesses its member heap instantiation single object access its member heap instantiation object array access its member code practice
Define a coordinate class that contains two data members: horizontal coordinates x and ordinate y, and two member functions, which are used to print the horizontal and vertical axes respectively.
#include <iostream>
#include <stdlib.h>
using namespace std;
Class coordinate
{public
:
int x;
int y;
void Printx ()
{
cout<< x <<endl;
}