cpp学习笔记02

由于时效问题,该文某些代码、技术可能已经过期,请注意!!!本文最后更新于:2 年前

如题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include<iostream>
#include<string>
using namespace std;


//值传递, 形参不会修饰实参
void swap1(int a, int b)
{
int tmp = a;
a = b;
b = tmp;

}

//地址传递,形参会修饰实参
void swap2(int *a, int *b)
{
int tmp = *a;
*a = *b;
*b = tmp;
}

//常量引用,用来修饰形参,防止误操作
void showValue(const int &val)
{
cout << val << endl; // val的值无法修改
}


//引用的本质是指针常量
//引用传递,形参会修饰实参
void swap3(int &a, int &b)
{
int tmp = a;
a = b;
b = tmp;
}

// 不要返回局部变量的引用
// int& test1()
// {
// int a = 10; // 局部变量存放在栈区
// // return a; // 返回引用会带来隐患
// }

// 函数的调用可以作为左值
int& test2()
{
static int a = 10; // 静态变量存放在全局区
return a;
}

int main(int argc, char const *argv[])
{
//引用的基本使用
//作用:给变量起别名
//语法:数据类型 &别名 = 原名
int a = 10;
// 创建引用
int &b = a; // 引用初始化(必须),初始化后不可改变,b的值也是10

int &aa = test2();
test2() = 100; // 函数的调用可以作为左值
cout << aa << endl;


return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include<iostream>
#include<string>
using namespace std;

//声明和实现只能有一个有默认参数,即如果函数声明有默认参数,函数实现就不能有默认参数,反之亦然
//函数声明
int func1(int a, int b=10);

//函数实现
int func1(int a, int b)
{
return a + b
}

// 占位参数
int func2(int a, int) // 第二个 int 为占位符,占位符也可有默认值, 如 int func2(int a, int = 10);
{
return a
}

//函数重载
//同一个作用域下
//函数名称相同
//函数参数类型不同,或者个数不同,或者顺序不同
// 函数的返回值不可以做为函数重载的条件

//引用做为重载条件
void func3(int &a)
{
cout << '' << endl;
}

void func3(const int &a)
{
cout << 'const' << endl;
}


int main(int argc, char const *argv[])
{
func3(10); // 运行 func3(const int &a), 因为 int &a = 10 不合法

return 0;
}

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!