C ++ learning began to die series: basic grammar 4

Learning C ++ is still the basis for this article let's start from the function.

function

Is a set of functions to perform a task with the statement. Each C ++ program has at least one function, i.e. the main function  main ()  , all simple program can define other additional functions.

Function declaration

Function declaration tells the compiler function name, return type and parameter. In the function declaration, the name of the parameter is not important, only the type parameter is required

return_type function_name( parameter list );

When a function is defined in the source file, and call a function in another file, the function declaration is necessary. At this point, you should call the function declaration function at the top of the file.

Defined functions

The general form of the function defined in C ++ as follows:

return_type function_name( parameter list ){  body of the function  }

In C ++, a function of the first function and a function of body composition. Listed below are a function of all components:

  • Return type: a function can return a value. return_type  is the data type of the value returned by the function. Some functions perform the required operations without the return value, in this case, the keyword return_type  void .
  • Function name: This is the actual name of the function. Function name and parameter list together constitute the function signature.
  • Parameters: parameter like a placeholder. When the function is called, you pass a value to the parameter, this value is called the actual parameters. Parameter list of function parameters include the type, order, quantity. Parameter is optional, that is, the function may not contain parameters.
  • Main function: function body contains a set of functions defined mission statement.

Call functions

When the program calls a function, program control will be transferred to the called function. When the function is defined tasks is called when the function return statement is executed, or reach the end brackets function, the program will return control to the main program.

The function is called, passing the required parameters, if the function returns a value, the return value may be stored.

Function parameters

Like other forms of local variables within the parameter of the function is created when entering the function, it is destroyed when the function exits. When you call the function, there are three ways to pass parameters to the function:

1. The call-by

The actual values of parameters of the copy to the formal parameters of the function. In this case, the parameter modifications do not affect the original function of the actual parameter. By default, C ++ using call-by- method to pass parameters. which is:

void swap(int x, int y);

2. pointer call

Passing parameters to a function pointer calls , the method of copying the address parameters to the formal parameters. Inside the function, the address for the actual parameters to use to access the call. This means that modification of parameters affect the actual parameters. which is:

void swap(int *x, int *y);

3. passed by reference

Copy the address reference to the formal parameters. Inside the function, the reference to the actual parameters to use to access the call. This means that modification of parameters affect the actual parameters. For example, swap:

// 函数定义
void swap(int &x, int &y)
{
   int temp = x; /* 保存地址 x 的值 */
   x = y;    /* 把 y 赋值给 x */
   y = temp; /* 把 x 赋值给 y  */ 
   return;
}

Optimized swap:

int swap(int& a, int& b)
{
    int temp = a ^ b;
    a = temp ^ a;
    b = temp ^ b;
    return 0;
}

Or use of different number of properties, a number equal to 0,0 with itself or with a different number of XOR does not change the number.

The default value of the parameter

Defining a function, you can specify a default value (the argument list for each parameter using the assignment operator to assign a parameter ). When you call the function, if the value of the actual parameter blank, the default value; if the value is specified, the default value is ignored, the values passed:

#include <iostream>
using namespace std;
 
int sum(int a, int b=20){return a+b;}

void main ()
{
   // 局部变量声明
   int a = 100,b = 200;
   // 调用函数来添加值
   cout << "Total value is :" << sum(a, b) << endl;
   // 再次调用函数
   cout << "Total value is :" << sum(a) << endl;
}

Lambda functions and expressions

C ++ 11 provides support for anonymous functions, called Lambda functions and expressions.

Lambda expressions to be seen as a function of the object. Lambda expressions can be used like an object, such as they can be assigned to variables and passed as parameters, like a function thereof may also be evaluated. Lambda expressions specific forms as follows:

[capture](parameters)->return-type{ body }

for example:

[](int x, int y) -> int { int z = x + y; return z + x; }

A temporary parameter z created to store intermediate results. As a general function, the value of z is not retained to the next unidentified function is called again. If the function does not return a lambda value (e.g. void), if the return type may be completely ignored.

Lambda expressions can be accessed within the current scope of the variable, which is Lambda expressions closure (Closure) behavior. This JavaScript different closures, C ++ variable transmission has passed by value and the difference between reference. By the foregoing  []  to specify:

[]      // 沒有定义任何变量。使用未定义变量会引发错误。
[x, &y] // x以传值方式传入(默认),y以引用方式传入。
[&]     // 任何被使用到的外部变量都隐式地以引用方式加以引用。
[=]     // 任何被使用到的外部变量都隐式地以传值方式加以引用。
[&, x]  // x显式地以传值方式加以引用。其余变量以引用方式加以引用。
[=, &z] // z显式地以引用方式加以引用。其余变量以传值方式加以引用。

Note: For the [=] or [&] form, lambda expressions can directly use this pointer. However, [] in the form of, if you want to use this pointer must explicitly pass (this write pointer within []):

//[capture](params){ body }
  [this]  ( ) { this-> someFunc();}();

computation

Built-in functions has a lot of functions for math, and math need to reference the header file  <cmath> in order to use them:

function                               description
double cos(double);    This function returns the cosine of the angle in radians (double type).
double sin(double); This function returns the sine of the angle in radians (double type).
double tan(double); This function returns the tangent of the angle in radians (double type).
double log(double); This function returns the natural logarithm.
double pow(double, double); The first parameter is assumed as x, the second argument is y, then the function returns the y-th power of x.
double hypot(double, double); This function returns the square root of the square sum of the two parameters, i.e., two parameters are at right angles to a side of the right triangle, the function returns the length of the hypotenuse.
double sqrt(double); This function returns the square root of the argument.
int abs(int); This function returns the absolute value of an integer.
double fabs(double); This function returns the absolute value of any of a float.
double floor(double); The function returns the largest integer not greater than the arguments passed.

random number

C ++ for the random number generator has two associated function (need to reference the header files  stdlib.h  ). A is   int RAND (void);  , only the function returns a pseudo-random number. It must be called before generating a random number  void srand (unsigned int seed);  function to set the random number seed (seed same, each random number sequence generated when the execution of the program is the same).

#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;

void main ()
{
   int i,randNum;
   // 设置种子
   // time() : time_t time(time_t *t),返回时间戳, 若参数 *t不为空,将返回值也存储在指针 t 指向的内存空间//
   srand( (unsigned)time( NULL ) );
   /* 生成 10 个随机数 */
   for( i = 0; i < 10; i++ ){ // 生成实际的随机数
      randNum= rand();
      cout <<"随机数: " << randNum << endl;
   }
}

Array

C ++ supports an array of data structures that can store a sequence of fixed size elements of the same type of collection. Declaration of an array is to declare an array variable, the array elements can be accessed through a specific index. All arrays are composed of contiguous memory locations. The lowest address corresponds to the first element, the highest address corresponding to the last element.

Declare an array

C ++ statements in one-dimensional array, the number of elements need to specify the types and elements, as follows:

type arrayName [ arraySize ];

arraySize  must be an integer constant greater than zero, type  may be any valid C ++ data types.

Array initialization

C ++, you can initialize the array elements one by one, can be used to initialize a statement:

double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};

The number of values ​​between the braces {} is not larger than the number of elements in an array we specify a statement in square brackets []. If omitted initialization of the size of the array, the array size, compared with the number of elements in the initialization.

Access Array

Array elements can be accessed through an array name indexed. Index of the element is placed in square brackets, followed behind an array of names. All are based on an array index 0 as the first element of which, also called based index, a last index of the array is the total size of the array minus one. The following array is discussed above graphical representation of the m:

Array representation

Multidimensional Arrays

The general form of a multidimensional array declaration is as follows:

type name[size1][size2]...[sizeN];

Two-dimensional array, in essence, is a list of a one-dimensional array, its declaration and initialization:

int a[2][3] = {  
 {0, 1, 2, 3} ,   /*  初始化索引号为 0 的行 */
 {4, 5, 6, 7} ,   /*  初始化索引号为 1 的行 */
};
//内部嵌套的括号是可选的,下面的初始化与上面是等同的
int a[2][3] = {0,1,2,3,4,5,6,7};

Pointer to an array

Array name is a constant pointer pointing to the first element of the array.

double *p,balance[10];
p = balance;

balance  is a point & balance [0] pointer, i.e., address of the first element of the array of balance. The  p  assigned to  balance  address of the first element. Use as a constant pointer array name is legal, and vice versa. Thus, * (balance + 4) is a balance [4] legitimate access to the data mode. note:

1. * p + 4 refers to the first address p is pointing to the array of balance (balance & [0]) of the pointer (& fetch address represents), p * is the address value of the first element (right side of an assignment * and expressions indicated value), which is the value plus 4 balance [0] +4 

2. * (p + 4) means a point p is the first address of the array balance (balance & [0]) of the pointer (& fetch address represents), p represents address plus 4 + 4, 4 + p * value again Therefore, * (p + 4) represents balance [4] (the value of the 5 elements).

In C ++, a  char *  or  char []  is transmitted to  cout  outputs, the result will be the entire string, if you want to get the address of the string (a character of the first memory address), method: mandatory conversion char *  other pointer ( void *, int *, * a float, Double * ):

#include <iostream>
using namespace std;

const int MAX = 3; 
void main ()
{
   char  var[MAX] = {'a', 'b', 'c'};
   char  *ptr;
   // 指针中的数组地址
   ptr = var;       
   for (int i = 0; i < MAX; i++){
      cout << "Address of var[" << i << "] = " <<  (int *)ptr ;
      cout << "Value of var[" << i << "] = " << *ptr;
      // 移动到下一个位置
      ptr++;
   }
}

Pass an array to a function

To pass an array as a parameter in the function must be declared in the following three ways in the form of function parameters. The results of these three statements is the same way, because each method will tell the compiler is to receive an integer pointer.

1. The parameter is a pointer in the form of:

void myFunction(int *param) { body of function }

2. The formal parameter is a defined array size:

void myFunction(int param[]) { body of function }

3. The formal parameter is an undefined array size:

void myFunction(int *param) { body of function }

Return an array from a function

The function returns from a one-dimensional array, you must declare the function returns a pointer:

int * myFunction(){ body of function }

C ++ does not support returning local variables outside the function address, except for the static  local variable. Example (// Returns an array of random numbers 10 from the function):

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
/* 要生成和返回随机数的函数 */
int * getRandom( ){
  static int  r[10];
  /* 设置种子 */
  srand( (unsigned)time( NULL ) );
  for (int i = 0; i < 10; i++){
     r[i] = rand();
     cout << "r[" << i << "] = " << r[i] << endl;
  }
  return r;
}
 
/* 要调用上面定义函数的主函数 */
void main ()
{
   /* 一个指向整数的指针 */
   int *p;
   p = getRandom();
   for (int i = 0; i < 10; i++ )
        cout << "*(p + " << i << ") : " << *(p + i) << endl ;
}
Published 161 original articles · won praise 90 · views 50000 +

Guess you like

Origin blog.csdn.net/qq_42415326/article/details/104017577