// 函数声明
int add(int a, int b);
就是cpp里的函数的具体实现
// 函数定义
int add(int a, int b) {
return a + b;
}
C++允许在同一作用域中声明多个具有相同名称但参数列表不同的函数
// 函数重载
int add(int a, int b);
double add(double a, double b);
递归函数是调用自身的函数。递归函数需要有一个终止条件,否则将无限循环
// 递归函数
int factorial(int n) {
if (n <= 1) {
return 1;
}
return n * factorial(n - 1);
}
类名(){}
[capture](parameters) -> return_type {
// 函数体
}
#include
int main() {
// Lambda 表达式,将两个数相加
auto add = [](int a, int b) -> int { //auto 用于自动推导变量的类型
return a + b;
};
// 使用 Lambda 函数
int result = add(3, 4);
std::cout << "The sum is: " << result << std::endl;
return 0;
}
void exampleFunction(int parameter1, float parameter2) {
// function body
}
int main() {
int a = 10;
float b = 3.14;
// 调用函数并传递实参
exampleFunction(a, b);
return 0;
}
#include
void byReference(int& x) {
x = x * 2;
}
void byValue(int x) {
x = x * 2;
}
int main(int argc, char** argv)
{
int a=2,b=2;
byValue(a);
byReference(b);
printf("a=%d\n", a);
printf("b=%d\n", b);
}
//结果为a=2;b=4
默认参数是在函数声明中为形参设置默认值,如果调用函数时没有提供对应实参,将使用默认值
// 函数声明,其中 b 的默认值为 10
void exampleFunction(int a, int b = 10);
// 函数定义
void exampleFunction(int a, int b) {
// 函数体
}
可以使用结构体、数组或类等方式实现函数返回多个值的效果
struct Point {
int x, y;
};
Point getCoordinates() {
Point p;
p.x = 10;
p.y = 20;
return p;
}
#include
int x = 5;
int& getVariable() {
return x;
}
int main(int argc, char** argv)
{
getVariable() = 10;
printf("x的值为:%d\n", x); // x 现在的值是 10
return 0;
}
函数可以返回指针,通常用于返回动态分配的内存
int* createInt() { //返回一个指向整数的指针 (int*)
int* ptr = new int; //使用 new 运算符在堆上动态分配了一个新的整数。这个新分配的内存的地址被存储在指针变量 ptr 中
*ptr = 42; //设置了这个内存位置的值
return ptr;
//return *ptr;如果这样写就是返回int型
}
通常用于实现链式调用(也叫流式接口)
在 C++ 中,& 符号用于声明引用
#include
struct MathOperations {
int value;
MathOperations& add(int x) {
value += x;
return *this;
}
MathOperations& multiply(int x) {
value *= x;
return *this;
}
};
int main() {
MathOperations result{5}; //value 成员初始化为 5
result.add(3).multiply(2);
std::cout << "Result: " << result.value << std::endl; // 输出:Result: 16
return 0;
}
// 头文件保护示例
#ifndef EXAMPLE_H
#define EXAMPLE_H
// 头文件内容
#endif
// 内联函数示例
#ifndef EXAMPLE_H
#define EXAMPLE_H
inline int add(int a, int b) {
return a + b;
}
#endif
void outerFunction() {
// 内部函数
void innerFunction() {
// 内部函数的实现
}
// 调用内部函数
innerFunction();
}