从C语言过渡到C++
一、引用
概念
给已存在变量取一个别名,编译器不会为引用变量开辟内存空间,它和它引用的变量共用同一块内存空间。
使用规则: 类型& 引用变量名 = 引用实体
#include <stdio.h>
int main()
{
int a = 100;
int &b = a;//b为a的空间引用
printf("a = %d\n", a);
printf("b = %d\n", b);
printf("address: a = %p\n", &a);
printf("address: b = %p\n", &b);
}
应用场景
交换两个数:
#include <stdio.h>
/*
//用C语言实现两个数的交换
void swap(int *a, int *b)
{
*a ^= *b;
*b ^= *a;
*a ^= *b;
}
*/
//用C++语言实现两个数的交换
int swap(int &a, int &b)
{
a ^= b;
b ^= a;
a ^= b;
}
int main()
{
int a = 100;
int b = 10;
printf("a = %d, b = %d\n",a,b);
// swap(&a,&b);
swap(a,b);
printf("a = %d, b = %d\n",a,b);
return 0;
}
二、默认参数
概念
默认参数是声明或定义函数时为函数的参数指定一个默认值。在调用该函数时,如果没有传对应的实参则采用该默认值,否则使用传入的实参。
应用场景
#include <stdio.h>
void debug(const char *ptr = "-------------------------")
{
printf("%s\n",ptr);
}
int main()
{
// debug("-------------------------------");
debug();
debug();
debug();
debug("hello");
debug("world");
return 0;
}
三、函数重载
概念
C++允许定义函数名相同,实参(名称,顺序,个数)不同的几个函数,常用来处理实现功能类似但数据类型不同的问题。
应用场景
#include <stdio.h>
#include <string.h>
/*
int int_cmp(int a ,int b)
{
return a-b;
}
int str_cmp(const char *str1 ,const char *str2)
{
return strcmp(str1,str2);
}
*/
int cmp(int a ,int b)
{
return a-b;
}
int cmp(const char *str1 ,const char *str2)
{
return strcmp(str1,str2);
}
int main()
{
// printf("%d\n",int_cmp(1,2));
// printf("%d\n",str_cmp("aaa","bbb"));
printf("%d\n",cmp(1,2));
printf("%d\n",cmp("aaa","bbb"));
}
四、堆内存
堆用于程序运行时动态内存分配,堆是可以上增长的
概念
C++提出了自己的内存管理方式:通过new和delete操作符进行动态内存管理。
应用场景
#include <stdio.h>
#include <malloc.h>
#include <string.h>
int main()
{
/*
char *p = (char *)malloc(10);
strcpy(p,"hello");
printf("p:%s\n",p);
free(p);
*/
int *intp = new int; //(int *)malloc(sizeof(int))
*intp = 100;
printf("*intp = %d\n",*intp);
delete intp;
char *p = new char[10];
strcpy(p,"hello");
printf("p =%s\n",p);
delete [] p;
}