Leyanshi
Articles4
Tags3
Categories1

Categories

一言

Archive

C++笔记 2026-05-24

C++笔记 2026-05-24

遇事不决 来杯瑞幸C++

Class (P8)

New thing(其实是老朋友)

Conception

  • Function(函数)在Java里叫Method(方法)。
  • Function 栈
    Zhan
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
int a(int x) { // x是形式参数,简称形参
x *= 100;
return x * 2;
}

int c(int* d) { // 注意这里的形参类型是指针类型
*d = 100;
//这里改变的不是d,而是指针指向的变量
return 1;
}

int main() {
int j = 114514;
c(&j); // 注意这里传入的实参要和函数需要的形参的类型一样,这里需要的是指针所以是&j而不是j
//返回的可以不设变量
int x = 1;
int res = a(x);
cout << x << " " << res; //1
return 0;
}
  • 函数调用的步骤:
  1. 保存执行断点(见第7步)
  2. 变参压栈 (新的局部变量 值从实参拷贝过来)
  3. 执行函数的代码
  4. 执行到return就返回
  5. 参数出栈
  6. 恢复断点(断点出栈)
  7. 继续执行从断点开始的调用之后的语句
  • Important thing: 函数传参
    形参变量的改变不影响实参。使用指针类型时,可以通过指针影响形参(实参)指向的变量,这会造成影响的假象。

Homework: 函数实现<utility> 内的 std::swap函数

1
2
3
4
5
6
7
8
9
#include <bits/stdc++.h>

using namespace std;

void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}