C++远征离港篇
离港总动员
C++远征计划的学习者肯定是冲着封装,继承,多态来的。
知识点:
- 指针 VS 引用
#define VS const(更强数据控制力)
- 函数默认值 & 函数重载
- 内存管理(头疼): 堆中的内存管理几乎完全由程序员操心[出来混总是要还的]
- 封装 继承 多态
c++语言引用
引用类型:
- 什么是引用?
引用就是变量的别名
- 能不能只有别名?
只有别名,别名就变成了真实姓名.只有别名也是无法进行命名的。
基本数据类型的引用
#include <stdlib.h>
#include <iostream>
using namespace std;
int main(void)
{
int a = 3;
// 给a起了一个别名b
int &b = a; //引用必须初始化
b = 10; // 给b赋值10,a的值也就由3变为10
cout << a << endl;
system("pause");
return 0;
}
为a起别名b: 对别名做的操作就是对a本身做了操作[叫小萝卜头干什么,罗某某也干了什么]
结构体类型的引用
使用别名对于结构体做操作的例子:
typedef struct
{
int x;
int y;
}Coor;
#include <stdlib.h>
#include <iostream>
using namespace std;
typedef struct
{
int x;
int y;
}Coor;
int main(void)
{
Coor c1;
Coor &c = c1; // 给c1起了别名c
c.x = 10; // 使用别名对真实值做操作
c.y = 20;
cout << c1.x << endl << c1.y << endl;
system("pause");
return 0;
}
指针类型的引用
类型 *&指针引用名 = 指针;
#include <iostream>
using namespace std;
int main(void)
{
int a = 10;
int *p = &a; // 定义指针p
int *&q = p; // 指针p的别名q
*q = 20;
cout << a << endl;
system("pause");
return 0;
}
int a = 10;
// 给a分配一个内存逻辑地址,如0x100001。这个地址存放了值10;int *p = &a;
//创建指针变量p指向a,给p分配地址0x100002,这个地址存放的值是"0x100001"(a的逻辑地址值);
-int *&q = p;
// (给指针p起别名q)创建变量q,给q分配地址也是0x100002, 因此这个地址存放的值还是a的逻辑地址值;*q = 20;
// (对q做操作)访问存放在q变量地址下的值,获得了a的地址值, 再访问一下a的地址值,修改里面存放的内容为20;
引用作为函数参数
C语言中将两个数的值进行交换:
void fun(int *a, int *b)
{
int c =0;
c =*a;
*a =*b;
*b =c;
}
int main()
{
int x =10;
int y =20;
fun(&x,&y);
return 0;
}
c++中引用实现:
void fun(int &a, int &b)
{
int c =0;
c =a;
a =b;
b =c;
}
int main()
{
int x=10,y=20;
fun(x,y)
return 0;
}
a是x的别名。b是y的别名。 里面操作的就是实际的参数了。
C++语言引用代码演示:
基本数据类型引用示例:
2-2-C++Two-ReferenceDemo/main.cpp
#include <iostream>
#include <stdlib.h>
using namespace std;
int main(void)
{
int a = 10;
int &b = a; // 定义一个引用(别名)
// int &b = NULL; 计算机会报错, 初始化 无法从 int 转换为 int &
b = 20;
cout << a << endl;
a = 30;
cout << b << endl;
system("pause");
return 0;
}
对于本体和别名的操作具有相同的效果。
结构体引用示例:
2-2-2-C++Two-ReferenceStructDemo/main.cpp
#include <stdlib.h>
#include <iostream>
using namespace std;
typedef struct
{
int x;
int y;
}Coord; //Coord 坐标
int main(void)
{
Coord c;
Coord &c1 = c; // 起别名c1
c1.x = 10;
c1.y = 20;
cout << c.x << endl << c.y << endl;
system("pause");
return 0;
}
指针引用示例:
2-2-3-C++Two-ReferencePointerDemo/main.cpp
#include <stdlib.h>
#include <iostream>
using namespace std;
int main(void)
{
int a = 3;
int *p = &a;
int *&q = p; // 指针p的别名q
*q = 5;
cout << a << endl;
system("pause");
return 0;
}
函数参数引用示例:
2-2-4-C++Two-ReferenceFunctionParameter/main.cpp
#include <stdlib.h>
#include <iostream>
using namespace std;
void fun(int &a, int &b);
int main(void)
{
int x = 10;
int y = 20;
cout << x << endl;
cout << y << endl;
fun(x, y);
cout << "交换后:" << endl;
cout << x << endl;
cout << y << endl;
system("pause");
return 0;
}
void fun(int &a, int &b)
{
int c = 0;
c = a;
a = b;
b = c;
}
看起来传入的是实参x,y 实际上 a是x的引用,b是y的引用
int a