Introduction To C++ functions-CSDN Blog
Introduction To C++ functions-CSDN Blog
Introduction To C++ functions-CSDN Blog
Article directory
Preface
Function basics
1. Define functions
2. Call function
3. Return value
Function parameters
1. Pass by Value
2. Pass by Reference
3. Pass by Pointer
Default parameter value
basic concept
Example
Usage scenarios and precautions
function overloading
Basic principles of function overloading
Example
Usage scenarios and precautions
recursive function
basic concept
Example: Calculate factorial
Usage scenarios and precautions
inline function
basic concept
Example
Usage scenarios and precautions
lambda expression
basic concept
Example
Detailed explanation of capture methods
1. Capture `[=]` by value
2. Capture `[&]` by reference
3. Explicit capture
4. Default capture and explicit mixing
5. Capture the `this` pointer
Usage scenarios and precautions
function template
basic concept
Example
Usage scenarios and precautions
Summarize
Next, I will continue to finish the basic knowledge of C++ first, and then improve the version a little bit, which is a bit in-depth! ! !
Friends who are interested, please like and follow
Preface
This article mainly discusses functions, templates and Lambda expressions in C++ .
1. Define functions
A function definition specifies what the function is to do. In C++, the definition of a function includes several key parts:
Return type : Indicates the data type returned by the function. If the function does not return any value, void the type is used.
Function name : The unique identifier of the function, used to call the function.
Parameter list : A parameter list in parentheses that specifies the variables passed to the function. If the function does not accept any paramete
be empty.
Function body : The code block within curly braces {} that defines the execution operation of the function.
This function accepts two integer arguments and returns their sum.
2. Call function
Once a function is defined, it can be called from other parts of the program. Calling a function means telling the program to execute the function's
For example, using the function defined above add :
1 int main() {
2 int result = add(5, 3);
3 std::cout << "The sum is: " << result << std::endl;
4 return 0;
5 }
Here, the function add(5, 3) is called add and the returned result is assigned to result the variable.
3. Return value
A function can return a value, which can be of any data type. The return type is specified in the function definition, and return the statement in t
function body is used to return the value. If the return type of a function is void , it means that the function does not return any value. For examp
function above add , return x + y; the statement returns the sum of the two arguments.
Code example:
1 #include <iostream>
2
3 // 函数定义
4 int add(int x, int y) {
5 return x + y; // 返回两个参数的和
6 }
7
8 int main() {
9 int a = 5;
10 int b = 3;
11
12 // 调用函数并接收返回值
13 int sum = add(a, b);
14
15 // 输出结果
16 std::cout << "The sum of " << a << " and " << b << " is: " << sum << std::endl;
17
18 return 0;
19 }
3. In the function, two integers and main are defined and passed as parameters to the function. a b add
4. add The return value of the function is assigned to the variable sum .
Function parameters
In C++, function parameters can be passed in three main ways: 值传递 , 引用传递 and 指针传递 . Each method handles parameters and affects ex
variables of the function differently.
1. Pass by Value
Concept : 值传递时 , function receives a copy of the argument. Any modification of parameters inside the function will be ignored 不会影响原始数
Features : Safe and simple, but may cause problems 额外的内存和时间开销 (especially for large structures or classes).
Example :
1 void modify(int x) {
2 x = 10; // 只修改了副本
3 }
4
5 int main() {
6 int a = 5;
7 modify(a);
8 // 'a' 仍然是 5,因为 'modify' 只修改了它的副本
9 }
2. Pass by Reference
Concept : Pass parameters by reference, and the function receives the reference (or alias) of the parameter. Any modification to the parameter
function directly affects the original data.
Features : Can avoid copying large data structures while allowing functions to modify the caller's data.
Example :
3. Pass by Pointer
Concept : Pass parameters through pointers, and the function receives the address of the parameter. Through this address, the function can m
original data.
Features : Similar to reference transfer, original data is allowed to be modified. But using a pointer is more flexible because it can receive a null
nullptr ), which means "no valid data".
Example :
1 void modify(int *x) {
2 if (x != nullptr) {
3 *x = 10; // 通过指针修改原始数据
4 }
5 }
6
7 int main() {
8 int a = 5;
9 modify(&a); Think it’s One-click
10 // 'a' 现在是 10,因为 'modify' 修改了它的原始数据 pretty good? collection
11 } shopeeai focus on twenty three 16
Default parameter value
In C++, default parameters are a very practical feature that allows you to specify default values for one or more parameters when defining a function
default values are used when this function is called without providing values for these parameters. This increases the flexibility of the function and re
number of overloaded functions that need to be written for different situations.
basic concept
Define default parameters : When , you can specify a default value 函数声明 for one or more . 参数
Calling a function with default parameters : When calling a function, you can omit parameters that have default values, or you can provide n
to override the default values.
Note : Default parameters can only 从右向左 be defined, that is, if a parameter has a default value, then all parameters to the right of it must als
default values.
Example
Suppose you have a function that calculates the sum of two numbers, where the second number has a default value:
1 #include <iostream>
2
3 // 函数声明,带有一个默认参数
4 int add(int x, int y = 10) {
5 return x + y;
6 }
7
8 int main() {
9 std::cout << "Add 5 and 3: " << add(5, 3) << std::endl; // 输出 8
10 std::cout << "Add 5 and default (10): " << add(5) << std::endl; // 输出 15,使用默认参数值
11
12 return 0;
13 }
In this example:
add The function has two parameters, x and y . y is given a default value of 10.
When calling add(5) , the second argument is omitted, so the default value of 10 is automatically used.
Usage scenarios : Default parameters are ideal for parameters that have "typical values" that do not change across most calls.
Precautions :
Default parameters should be 函数声明 defined in , not in the function definition (if the function declaration and definition are separate).
If a function is declared in multiple places (such as in different header files), then the default parameters should be declared in only one pla
The values of default parameters are determined when the function is called, not when the function is defined.
function overloading
Function overloading allows you 相同的函数名 to define multiple functions as long as they are 参数列表(参数的类型、数量或顺序) different. This increa
readability and flexibility because you can use the same function name for similar operations.
Different argument lists : Functions can be overloaded as long as they are 参数列表 different. This difference can be achieved by changing the
type, or order of parameters.
The return type is not a basis for overloading : simply having a different return type is not enough to constitute a function overloading. Even
type is different, the parameter list must be different.
Call-time matching : When an overloaded function is called, the compiler determines which version of the function to use based on the type an
of arguments provided.
Think it’s One-click
Example pretty good? collection
shopeeai twenty three 16
Here is an example of function overloading, using the same function name (focus on
print ) to handle different types or numbers of arguments:
1 #include <iostream>
2
3 // 打印整数
4 void print(int i) {
5 std::cout << "Printing int: " << i << std::endl;
6 }
7
8 // 打印浮点数
9 void print(double f) {
10 std::cout << "Printing float: " << f << std::endl;
11 }
12
13 // 打印两个整数
14 void print(int i, int j) {
15 std::cout << "Printing two ints: " << i << ", " << j << std::endl;
16 }
17
18 int main() {
19 print(5); // 调用 print(int)
20 print(5.5); // 调用 print(double)
twent print(5, 10); // 调用 print(int, int)
twent
twent return 0;
twent}
In this example, print the function is overloaded three times: once to print an integer, once to print a floating point number, and once to print two in
simultaneously.
Usage scenarios : Function overloading is ideal for scenarios that perform similar operations but have different parameter types or numbers.
Precautions :
Be careful when using overloading to ensure that the behavior of each function version is clear and expected to avoid ambiguity when callin
Excessive use of overloading can lead to code that is difficult to understand and maintain, especially when functions have multiple paramet
recursive function
In C++, a recursive function is a function that calls itself. Recursion can be used to solve problems that can be broken down into similar sub-problem
especially useful when working with data structures (such as trees and graphs) or performing algorithmic operations (such as sorting and searching)
basic concept
Basic case : Every recursive function should have one or more exit conditions that terminate the recursion that do not involve recursive calls.
Recursive case : The portion of a recursive function where the function calls itself to solve a subproblem.
A typical example of a recursive function is calculating the factorial of an integer. The factorial n! is defined as the product of all integers from 1 to n,
1 #include <iostream>
2
3 // 递归函数来计算阶乘
4 int factorial(int n) {
5 if (n <= 1) {
6 return 1; // 基本情况:0! = 1! = 1
7 } else {
8 return n * factorial(n - 1); // 递归情况
9 }
10 }
11
12 int main() {
Think it’s One-click
13 int num = 5;
pretty good? collection
14 std::cout << "Factorial of " << num << " is " << factorial(num) << std::endl;
shopeeai focus on twenty three 16
15
16
16
return 0;
}
In this example, factorial the function calls itself to calculate the factorial of smaller integers until the exit condition ( n <= 1 ) is reached.
Usage scenarios : Recursion is very suitable for processing tasks that can be naturally decomposed into smaller and simpler sub-problems, su
traversal, certain mathematical problems, etc.
Precautions :
Make sure the recursion has an exit condition to avoid infinite recursion.
Recursive functions can consume a lot of memory, especially if they are deeply recursive.
inline function
Inline functions are a feature provided by C++ to optimize small, frequently called functions. When a function is declared inline, the compiler attempt
all calls to the function directly with the code of the function itself. This can reduce the overhead of function calls, especially in loops or frequent call
basic concept
Define inline functions inline : Define inline functions by adding the keyword before the function declaration .
How it works : The compiler replaces inline functions with the corresponding function code at each call point.
Usage scenarios : Usually used for small functions, such as simple accessors or modifiers, which only have a few lines of code.
Example
1 #include <iostream>
2
3 inline int max(int x, int y) {
4 return (x > y) ? x : y; // 返回 x 和 y 中的最大值
5 }
6
7 int main() {
8 std::cout << "Max of 10 and 20 is " << max(10, 20) << std::endl;
9 return 0;
10 }
In this example, max the function is defined inline. This means that when calling max(10, 20) , the compiler may directly (10 > 20) ? 10 : 20 rep
call with , thereby reducing the overhead of a function call.
Usage scenarios : For very short, frequently called functions, such as simple mathematical operations, conditional judgments, or accessor func
Precautions :
Inlining is simply a request to the compiler, which the compiler can choose to ignore.
Inlining large or recursive functions can lead to code bloat (increased program size).
Excessive use of inlining may reduce the overall performance of your program.
The definition of an inline function must precede the call or be in the same file as the call so that the compiler can replace it at compile time
lambda expression
Lambda expressions are a feature introduced in C++11 and subsequent versions that allow anonymous functions to be defined in code. Lambda ex
are a convenient way to write inline functions, especially when they need to be passed as parameters to algorithms or other functions.
basic concept
Anonymous function : A Lambda expression is essentially a function without a name. Think it’s One-click
pretty good? collection
Syntax : Usually of the form [capture](parameters) -> return_type { body } , most of the elements can be omitted if desired.
shopeeai focus on twenty three 16
Capture list : Lambda expression uses capture list to access variables in its scope.
Parameters and return types : Like ordinary functions, Lambda can have parameters and return types. The return type specification can be om
lambda body contains only a return statement, or if the return type is void .
Example
Here is an example of a Lambda expression that demonstrates how to define and use Lambda expressions:
1 #include <iostream>
2 #include <vector>
3 #include <algorithm>
4
5 int main() {
6 std::vector<int> numbers = {1, 2, 3, 4, 5};
7 int factor = 2;
8
9 // 使用
Lambda 表达式来操作每个元素
10 std::for_each(numbers.begin(), numbers.end(), [factor](int &n) {
11 n *= factor; // 每个元素乘以因子
12 });
13
14 // 输出结果
15 for (int n : numbers) {
16 std::cout << n << " ";
17 }
18 std::cout << std::endl;
19
20 return 0;
twent}
In this example, Lambda expressions are used std::for_each in the algorithm to numbers operate on each element of the vector. Lambda
[factor] captures an external variable factor so that it can be accessed within the Lambda body.
The capture list of a lambda expression defines the external variables that can be accessed within the body of the lambda. Depending on how th
captured, these variables can be captured by value, by reference, or otherwise.
Behavior : When capturing by value, the Lambda expression captures the external variables in the value capture list, and each variable is capt
copy of its value at the time the Lambda was created.
Features : The captured copy is a constant in the Lambda body, unless mutable the keyword is added after the parameter list.
Example :
1 int x = 10;
2 auto lambda = [=]() mutable { x = 42; }; // 'x' 是副本
3 lambda();
4 // 原始的 'x' 保持不变,仍为 10
Behavior : When capturing by reference, the Lambda expression places the external variable capture value in the capture list, and the variable
by reference.
Features : Any modification to these variables within the Lambda body will affect the original variables.
Example :
1 int x = 10;
2 auto lambda = [&]() { x = 42; }; // 'x' 是引用
3 lambda();
4 // 原始的 'x' 现在变为 42
Think it’s One-click
pretty good? collection
3. Explicit capture shopeeai focus on twenty three 16
Behavior : Specific variables can be captured explicitly by value or by reference.
Example :
1 int x = 10, y = 20;
2 auto lambda = [x, &y]() { /* 使用 'x' 的副本和 'y' 的引用 */ };
Behavior : You can mix default capture methods (all by value or all by reference) with explicitly specified methods.
Example :
1 int x = 10, y = 20;
2 auto lambda = [=, &y]() { /* 按值捕获除 'y' 外的所有变量,'y' 通过引用捕获 */ };
3 auto lambda2 = [&, x]() { /* 按引用捕获除 'x' 外的所有变量,'x' 通过值捕获 */ };
Behavior : In a class member method, you can capture this a pointer to access the class member.
Example :
1 class Example {
2 int value = 10;
3 public:
4 void method() {
5 auto lambda = [this]() { return value; };
6 }
7 };
Usage scenarios : Lambda expressions are very suitable for scenarios that require temporary function objects, such as passing them as param
algorithms, or defining simple callback functions.
Precautions :
Variables in the capture list can be captured by value ( [=] ), by reference ( [&] ), or mixed ( [=, &foo] ).
The type of a lambda expression is unique and unnameable. If a type is required, you can use auto the keyword or std::function .
Pay attention to life cycle issues when capturing external variables to ensure that the variables captured by Lambda are still valid when use
function template
Function templates are a powerful tool for implementing generic programming in C++. It allows writing code that is independent of specific data type
means that the same piece of code can be used to handle different types of data without having to write duplicate functions for each data type.
basic concept
Generic programming : Function templates are part of generic programming. The goal of generic programming is to make algorithms as indep
possible of the data types used.
Template definition : A function template template begins with the keyword, followed by a list of template parameters, which are type or non-t
parameters.
Type parameters : represent a data type. When using templates, these parameters are replaced by specific types.
Non-type parameter : represents a value rather than a type. It can be an integer or a pointer to a certain type, etc.
Example
Here is a simple function template example that defines a template function that exchanges two values:
In this example, Swap function templates can be used for any data type. When used with int , double or any other type, the compiler generates a s
function instance for each type.
Usage scenarios : Function templates are particularly suitable for algorithms whose basic operations (such as comparison, exchange, copy, et
independent of the data type of the operation.
Precautions :
Template code should be kept concise to avoid overly complex code when instantiating.
Certain complex situations may require template specialization, an advanced feature in template programming that allows you to provide sp
implementations for specific types.
Summarize
This article mainly introduces some knowledge related to C++ functions from the aspects of function basics, parameter passing, default parameters,
overloading, recursive functions, inline functions, Lambda expressions, and function templates.
Next, I will continue to finish the basic knowledge of C++ first, and then improve the version a little bit, which is a bit in-dep
Introduction to C++ [30- C++ Date & Time] Knowledge changes des
The C++ standard library does not provide a so-called date type. C++ inherits C language structures and functions for date and time operations . In order to use date and
[Likou·Daily Question] 83. Delete duplicate elements in the sorted linked list (linked list thinking traverses C++ Go in one go) We all have a bright fu
Given the head of a sorted linked list, remove all duplicate elements so that each element appears only once. Returns a sorted linked list. Because the given linked list ha
(C语言)冒泡排序 m0_67184754 的
【代码】(C语言)冒泡排序。
C++ 轮子·STL 简介 chenyuping333 的
大部分人提到 C++ 标准库的时候首先想到的就是STLSTL的全称是,它背后的技术支撑是模板,由于很多人对于模板本身的不了解,导致很多人对于STL的理解也非常的片
c++ 函数指针详细介绍
函数指针是指向函数的指针变量。与指向变量的指针类似,指向函数的指针变量存储的是函数的地址。通过函数指针,可以在程序运行时动态地调用函数,这对于实现回调
“ 相关推荐”对你有帮助么?
Very unhelpful Not helpful generally helpful very helpful
shopeeai
6 years of University of Sci…
popular articles
latest comment
latest articles
4 articles in 2020
Table of contents
Article directory
Preface
Function basics
1. Define functions
2. Call function
3. Return value
Function parameters
1. Pass by Value
2. Pass by Reference
3. Pass by Pointer
Think it’s One-click
Default parameter value
pretty good? collection