An overview of the content and knowledge structure to be studied



The parameters of a function and how they are passed

1. Function parameter passing mode

By value:

Pass variable value: copy the contents of the argument memory to the parameter, which are two different pieces of memory

Pass address value: the parameter is given the address value of the memory space corresponding to the argument. The parameter is a pointer to the memory space corresponding to the argument

The reference:

A parameter is a reference to an argument, which is in the same block of memory as the argument

2. Object as function parameter, that is, pass variable value

Pass the value of the argument object to the parameter object, which is the backup of the argument. When changing the value of the parameter in a function, it is the backup value that is changed, without affecting the original value

Like this:

void fakeSwapAB(int x , int y) {
    int temp = x;
    x = y;
    y = temp;
}

int a = 5;
int b = 8;
cout << "Before the exchange:" << a << ","<< b << endl; FakeSwapAB (a, b); cout <<"After the exchange:" << a << "," << b << endl;
Copy the code

3. Object pointer as function parameter, that is, pass address value

Parameter is the object pointer, argument is the address of the object value, although the parameter passing way is still, by value because of the parameter and argument address values, so they all point to the same block of memory, we through the pointer changes is pointing to the contents of the memory, so when through the parameter in the function change the values in the memory, change is the value of the original argument

Like this:

void realSwapAB(int * p, int * q) {
    int temp = *p;
    *p = *q;
    *q = temp;
}

int a = 5;
int b = 8;
cout << "Before the exchange:" << a << ","<< b << endl; RealSwapAB (&a, &b); cout <<"After the exchange:" << a << "," << b << endl;
Copy the code

In the case of an array, since the name of the array is the first address of the array, you can also pass the value of the array address

void swapArrFirstAndSecond(int a[]) {
    int temp = a[0];
    a[0] = a[1];
    a[1] = temp;
}

int main(int argc, const char * argv[]) {
    
    int a[] = {2, 3};
    cout << "Before the exchange:" << a[0] << "," << a[1] << endl;
    swapArrFirstAndSecond(a);
    cout << "After the exchange:" << a[0] << "," << a[1] << endl;
    return 0;
}
Copy the code

4. Reference as function argument, i.e. pass address (note: this is not the address value)

When the function is called, the argument object name is passed to the parameter object name, which becomes the alias of the argument object name. The argument object and the parameter object represent the same object, so changing the value of the parameter object changes the value of the argument object

Like this:

void citeSwapAB(int & x, int & y) {
    int temp = x;
    x = y;
    y = temp;
}

int a = 5;
int b = 8;
cout << "Before the exchange:" << a << ","<< b << endl; CiteSwapAB (a, b); cout <<"After the exchange:" << a << "," << b << endl;
Copy the code

Advantage: the reference object is not an independent object, not only exclusive memory unit, and the object pointer to open up another memory unit (memory to put the address passed by the argument), so pass the reference is better than pass the pointer.

5. Default parameters

The program is not required to set this parameter when it is called. Instead, the compiler assigns the parameter a default value when needed.

Rule 1. Specify explicitly when a program needs to pass a specific value. Default arguments must be specified in the function prototype.

If the function is defined after main and the default parameters are set in the declaration, there is no need to set the default parameters in the definition

Like this:

Void PrintValue(int a, int b = 0, int c = 0); Int main(const char * argv[]) {// call PrintValue(5);return0; Void PrintValue(int a, int b, int c) {cout <<"a = " << a << endl;
    cout << "b = " << b << endl;
    cout << "c = " << c << endl;
}
Copy the code

If the function is defined before the main function, the default arguments are set in the definition

Like this:

Void PrintValue(int a, int b = 0, int c = 0) {cout <<"a = " << a << endl;
    cout << "b = " << b << endl;
    cout << "c = "<< c << endl; } int main(int argc, const char * argv[]) {return 0;
} Copy the code

Rule 2: There can be more than one default argument, but it must be at the end of the argument sequence.

Like this:

There can be a default argument:

void PrintValue(int a, int b, int c = 0);
Copy the code

There can be multiple default arguments:

void PrintValue(int a, int b = 0, int c = 0);
Copy the code

Default parameters cannot be set in the middle:

void PrintValue(int a, int b = 0, int c);
Copy the code

Rule 3. If a default argument needs to be specified with a specific value, all arguments that precede it must be assigned

PrintValue(5, 8, 9); PrintValue(5, 8, 9); PrintValue(5, 8); PrintValue(5,, 9); /* PrintValue(5,, 9); /* PrintValue(5,, 9);Copy the code

6. Protect data with const

Use const to modify the parameter to be passed. This function can only use the parameter, but has no right to modify the parameter, to improve the system’s own security.

Like this:

Void catStr(const string STR) {string str2 = STR +" Ray!"; // A const modifier cannot be modified inside a function, so // STR = cannot be used"Hi"; cout << str2 << endl; } int main(int argc, const char * argv[]) {// instantiate a string STR ="Hello"; // Call the function catStr(STR);return 0;
}
Copy the code

Function return value

C++ functions can return value types of any type other than divisor and function

When the return value is a pointer or reference object, it is important to note that the object to which the function returns must exist. Therefore, the local object inside the function cannot be used as the return value, because the memory of the local variable or object inside the function is freed after the function is finished

1. Return the referenced function

A function can return a reference in order to place the function to the left of the assignment operator

Format: data type & function name (argument list);

Like this:

Int arr[] = {2, 4, 6, 8}; Int & getValueAtIndex(int I) {return arr[i];
}

int main(int argc, const char * argv[]) {
    
    cout << "Before change:"<< arr[2] << endl; GetValueAtIndex (2) = 10; getValueAtIndex(2) = 10; cout <<"After change:" << arr[2] << endl;
    
    return 0;
}
Copy the code

2. Functions that return Pointers

The return value is the memory address where data of a particular data type is stored. These functions are called pointer functions

Format: data type * function name (argument list);

Like this:

Int * p = new int[n]; int * p = new int[n]; int * p = new int[n]; // Assign a value to the requested memory spacefor(int i = 0; i < n; i++) { p[i] = i + 10; } // Return the first address of the memory spacereturnp; } int main(int argc, const char * argv[]) {int * p = getData(5); // Print the contents of the memory to which the pointer pointsfor (int i = 0; i < 5; i++) {
        cout << p[i] << endl;
    }
    
    return 0;
}
Copy the code

3. Functions that return objects

Format: data type function name (argument list);

Like this:

String sayHello(string s) {// We concatenate a string, and give STR string STR ="Hello "+ s; // and return STRreturnstr; } int main(const char * argv[]) {string STR = sayHello(const char * argv[])"Ray");
    cout << str << endl;
    
    return 0;
}
Copy the code

4. Function return values as function parameters

If a function returns a value as an argument to another function, the return value must be the same as the argument type of the other function

Like this:

Int getMax(int x, int y) {returnx > y ? x : y; } int main(int argc, const char * argv[]) { Int maxValue = getMax(5, getMax(8, 9)); cout << maxValue << endl;return 0;
}
Copy the code

Inline function

1. The concept of inline functions

A function that uses the keyword inline is called an inline function. An inline function must be defined before the statement that first calls the function appears in the program, so that the compiler knows its function and then substitutes it

Like this:

Inline bool isNumber(char c) {inline bool isNumber(char c) {if (c >= '0' && c <= '9') {
        return true;
    } else {
        return false; }} int main(const argc, const char * argv[]) { Cin >> c; // The isNumber(c) function is replaced by the body of the isNumber() function during programmingif (isNumber(c)) {
        cout << "I entered a number." << endl;
    } else {
        cout << "It's not a number." << endl;
    }
    
    return 0;
}
Copy the code

2. Note:

In C++, all functions can be described as inline except for functions with loop statements and switch statements.

3. :

Using inline functions can improve the execution speed of the program, but if the function body is too many statements, it will increase the amount of code.

Function overloading and default arguments

1. Function overload

A function name has multiple functions, has multiple morphologies, and I call this polymorphism, one name, multiple functions

Function overload must satisfy the following conditions:

The parameter type or number of parameters varies

Like this:

Int sumWithValue(int x, int y) {returnx + y; Int sumWithValue(int x, int y, int z) {returnx + y + z; } double sumWithValue(double x, double y) {returnx + y; } // sumWithValue(double x, double y, double z) {returnx + y + z; } int main(int argc, const char * argv[]) {int sumValue1 = sumWithValue(8, 9); Int sumValue2 = sumWithValue(8, 9, 10); Double sumValue3 = sumWithValue(1.2, 2.3); double sumValue3 = sumWithValue(1.2, 2.3); Double sumValue4 = sumWithValue(1.2, 2.3, 3.4); cout << sumValue1 << endl; cout << sumValue2 << endl; cout << sumValue3 << endl; cout << sumValue4 << endl;return 0;
}
Copy the code

2. Function overloading and default arguments

When function overloading is combined with default parameters, it can effectively reduce the number and form of functions and reduce the size of the code.

In this way, we can complete our function by keeping only one function per data type, eliminating two functions directly.

Like this:

Int sumWithValue(int x = 0, int y = 0, int z = 0) {returnx + y + z; } double x = 0, double y = 0, double z = 0;}returnx + y + z; } int main(int argc, const char * argv[]) {int sumValue1 = sumWithValue(8, 9); Int sumValue2 = sumWithValue(8, 9, 10); Double sumValue3 = sumWithValue(1.2, 2.3); double sumValue3 = sumWithValue(1.2, 2.3); Double sumValue4 = sumWithValue(1.2, 2.3, 3.4); cout << sumValue1 << endl; cout << sumValue2 << endl; cout << sumValue3 << endl; cout << sumValue4 << endl;return 0;
}Copy the code

If default parameters are used, you cannot overload functions with fewer parameters than the default number. You can overload functions with more parameters than the default number.

Like this,

Int sumWithValue(int x = 0, int y = 0, int z = 0) {returnx + y + z; Int sumWithValue(int x, int y) {// sumWithValue(int x, int y) {//returnx + y; Int sumWithValue(int x, int y, int z, int t) {sumWithValue(int x, int y, int z, int t) {returnx + y + z + t; } int main(int argc, const char * argv[]) {int sumValue1 = sumWithValue(8, 9); Int sumValue2 = sumWithValue(8, 9, 10); Int sumValue3 = sumWithValue(8, 9, 10, 11); cout << sumValue1 << endl; cout << sumValue2 << endl; cout << sumValue3 << endl;return 0;
}
Copy the code

A function template

As can be seen above, they are functions with exactly the same logical function and the same function body provided. The only difference is that the data type is different. In order to deal with them uniformly, function templates are introduced.

Now we have reduced our functions from four to one, but instead of reducing our functions, we have increased them. So for example, we can compute char, float

1. What are function templates

This flexibility is enhanced by using virtual parameter parameters rather than actual existing types when programming.

When instantiating such a function with an actual type, it is like creating a new function from a template, so it is called a function template

Format: Type parameters are usually identified by T, but others can be used

Template <class T> 

Like this:

SumWithValue (T x, T y) {sumWithValue(T x, T y) {returnx + y; } int main(int argc, const char * argv[]) {// Call the template function int sumValue1 = sumWithValue(3, 5); Double sumValue2 = sumWithValue(3.2, 5.1); cout << sumValue1 << endl; cout << sumValue2 << endl;return 0;
}
Copy the code

When a function template is used in conjunction with a specific data type, a template function is produced, also known as a function template instantiation

2. Parameters of the function template

Function template name < template parameters >(parameter list);

We can cast the data in the argument list to the specified data type

Like this,

Int sumValue2 = sumWithValue<int>(3.2, 5.1);Copy the code

We cast the data in the argument list to int and participate in the calculation

Can also like:

Double sumValue2 = sumWithValue(3.2, (double)5);Copy the code

We can also cast a single parameter in the parameter list and participate in the calculation

But we don’t usually use template arguments.

3. Use the keyword typename

The purpose is to replace the keyword class in the template argument list

Like this,

template <typename T>

Just replace class with typename, and use everything else.

It is highly recommended that you use typename because it is for templates, and class was used before typename. It also defines classes, which is not intuitive, and causes errors in some other places.

Conclusion:

It may be a little confusing for beginners, including me, but don’t think too complicated, it’s just a piece of code with a specific function, but we give it a name, so that it can improve the readability and maintainability of the code.

This series will continue to be updated! Everyone is eager to leave their own footprints!

👣 👣 👣 👣 👣 👣 👣 👣