" 以梦为马 不负韶华 "
这篇文章将带我们了解到(以后内容将头文件省略):
概念:引用是变量的一个别名(但是只存在别名是行不通的)
int main()
{
int a = 3;
int &b = a;//引用必须初始化
b = 10;//改变引用的值、也就对应改变了其变量的值
cout<< a <<endl;
return 0;
}
typedef struct
{
int x;
int y;
}Coor;
int main(void)
{
Coor c1;
Coor &c = c1;
c.x = 10;
c.y = 20;
cout<< c1.x <<endl;
cout<< c1.y <<endl;
return 0;
}
int main(void)
{
int a = 10;
int *p = &a;
int *&q = p;
*q = 20;
cout<< a <<endl;
return 0;
}
C语言
其中涉及到了C语言中较难的一个知识点——指针在实参和形参之间的传递过程(代码中、将x和y的地址作为实参分别传递给指针 *a 和 *b 、既完成了地址的传递也完成了值的传递)
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++
&a和&b分别是x和y的引用、改变a和b的值也就对应改变了x和y
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;
}
int x = 3;//变量
const int x = 3;//常量
const int *p = NULL;
int const *p = NULL;
//完全等价
const int *const p =NULL;
int const * const p = NULL;
//完全等价
1. int x = 3;
const int *p = &x;
//p = &y;正确
//*p = 4;错误
2. int x = 3;
int *const p = &x;
//p = &y;错误
const int x = 3;
const int *const p = &x;
//p = &y;*p = 4;错误
1. int x = 3;
const int &y = x;
//x = 10;正确
//y = 20;错误
1. const int x = 3; x = 5;
2. int x = 3; const int y = x; y= 5;
3. int x = 3; const int *y = &x; *y = 5;
4. int x = 3,z = 4; int *const y = &x; y = &z;
5. const int x = 3; const int &y = x; y = 5;
6. const int x = 3; int *y = &x;
int main()
{
int x = 3;
int y = 5;
int *const p = &x;
*p = 10;
cout<< x <<endl;
system("pause");
return 0;
}
int main()
{
int x = 3;
int y = 5;
int const*p = &x;
p = &y;
cout<< x <<endl;
system("pause");
return 0;
}
int main()
{
int x = 3;
int y = 5;
int const &z = x;
z = 10;
cout<< x <<endl;
system("pause");
return 0;
}
int main()
{
int x = 3;
int y = 5;
fun(x,y);
cout<< x << "," << y <<endl;
system("pause");
return 0;
}
void fun(const &a,const &b)
{
a = 10;
b = 20;
}
void fun(int i,int j = 5,int k = 10);
//正确
void fun(int i,int j = 5,int k);
//错误
void fun(int i,int j = 5,int k = 10);
//声明函数
void fun(int i,int j,int k);
//定义函数
void fun(int i,int j = 5,int k = 10);
void fun(int i,int j,int k);
{
cout<< i << j << k;
}
int main()
{
fun(20);
//输出20 5 10
fun(20,30);
//输出20 30 10
fun(20,30,40);
//输出20 30 40
return 0;
}
getMax(int x,int y,int z)
//新函数名getMax_int_int_int
getMax(double x, double y)
//新函数名getMax_double_double
int main()
{
int i = 10;j = 20,k = 30,m;
m = max(i,j,k);
cout<< "max = " << m <<endl;
return 0;
}
int max(a,b,c)
{
if(b>a)
a = b;
if(c>a)
a = c;
returm a;
}
int main()
{
int i = 10;j = 20,k = 30,m;
int a,b,c;
a = i;b = j;c = k;
if(b>a) a = b;
if(c>a) a = c;
m = a;
cout<< "max = " << m <<endl;
return 0;
}
int *p = new int;
//申请内存
delete p;
//释放内存
int *arr = new int[10];
//申请块内存
delete [ ]arr;
//释放块内存
void *malloc(size_t size);
void free(void *memblock);
new
delete
int *p = new int[1000];
if(NULL == p)
{
//内存分配失败
}
int *p = new int;
if(NULL == p)
{
//内存分配失败
//异常处理
}
delete p;
p = NULL;
int *p = new int[1000];
if(NULL == p)
{
//内存分配失败
//异常处理
}
delete [ ]p;
p = NULL;