1.指针的引用
struct Teacher
{
int age;
};
int hhh(Teacher ** t)
{
if (t==NULL)
{
return 0;
}
Teacher * tem = NULL;
tem =(Teacher*) malloc(sizeof(Teacher));
tem->age = 50;
*t = tem;
}
void hhh2(Teacher * & tem)//这种形式就是指针引用的语法规则;
{
tem = (Teacher*)malloc(sizeof(Teacher));
tem->age = 100;
}
void freepoint(void * b)
{
if (b==NULL)
{
return;
}
free(b);
}
void main()
{
Teacher * t=NULL;
//在c语言中,传入二级指针的方式
hhh(&t);
cout << t->age << endl;
freepoint(t);
//在c++中传入指针的引用来实现
hhh2(t);
cout << t->age << endl;
freepoint(t);
system("pause");
}
2.常量引用,及其初始化
void main()
{
//常引用 const修饰的引用 用变量初始化常量引用;
int a = 10;
const int & b = a;//常量引用让变量只有只读的属性,不能通过b去修改a;
//b=20; //这样做就会报错。
//用字面量初始化常量引用
//int & c=20; // 这是错误的,引用就是内存块的别名,但是20是字面量没有内存;但是加上const就可以了
const int & c = 20;//因为这还写在符号表中的;
//常量引用做函数参数的时候,这个通过引用去修改;
system("pause");
}
3.C++对C的函数的扩展
3.1内联函数:替代C中的宏定义代码块;内联函数必须和函数体的实现是在一体的,不能分开;代码最终不能生成这么一个函数,机械的替换调用的地方,和宏定义是一样的原理;在内联函数中不能存在循环和条件判断,否则编译器不能当做内联函数编译,当做普通函数的使用;
语法规则,在普通的函数返回关键字前面加个inline
inline void getString()
{
}
//带参数的宏定义
#define FEMO(a,b) ((a<b)?a:b)
inline int femo(int a,int b)
{
return a < b ? a : b;
}
void main()
{
int a = 2;
int b = 5;
int c=FEMO(a, b);
int c=femo(a,b);
system("pause");
}
3.2函数的默认参数:
void aaa(int a = 3)//这里a=3就是默认的
{
}
//如果有多个参数,多个默认参数的时候,默认的参数必须从右往左写;
//这样规定是防止在调用的时候,函数参数的传入问题;
int aaa2(int a,int b,int c=4,int d=12)
{
return a + b + c + d;
}
void main()
{
aaa(4);//填写参数的使用填的,不填使用默认参数
aaa();
aaa2(1,12);//至少传两个参数
system("pause");
}
3.3函数重载,函数名的右边不一样就形成重载,但是要注意和默认参数的函数重载的时候的问题,存在二义性,两个参数和一个默认参数,重载成两个参数,在调用的时候输入两个参数,编译器不知道该调用那个方法了;
3.4 函数指针遇上函数重载
//声明一个函数类型
typedef void (fuec3)(int a,int b);
//fuec * f=NULL;//这个函数指针指向函数的入口;
//声明一个函数指针类型,指向一个函数的入口;
typedef void (*fuec2)(int a,int b);
//定义一个函数指针变量
void (*fuec1)(int a, int b);
void aaa(int a)
{
}
void aaa(int a,int b)
{
}
void main()
{ //当函数指针遇上函数重载的时候
fuec2 a = aaa;
a(1,2);//这里调用的时候取决于声明的函数指针类型的参数类型和个数
system("pause");
}