C到C++扩展(2)

本文深入解析C++中的引用概念,包括寄存器变量、子函数局部变量引用、形参引用、常引用等,并探讨默认参数、占位参数及函数重载的使用技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1,register关键字

#include <iostream>
using namespace std;
int main()
{
	register int a = 100;
	&a;				//C中不允许对寄存器变量取地址操作,但C++可以
	return 0;
}

2,引用 &(当奇怪语法出现时)

#include <iostream>
using namespace std;
struct test
{
	int &a;				//当成指针来分析
	char &b;
	double &c;
};
int main()
{
	int a = 1;
	char b = 'm';
	
	int &c = a;
	char &d = b;
	cout << sizeof(c) << endl;		//不用关心编译器是怎么实现的(正常的语法现象)
	cout << sizeof(d) << endl;
	cout << sizeof(test) <<endl;		//当分析奇怪的语法现象时,需要考虑具体的引用实现(常指针)。eg:char str[32] = {0}; 	str++ 常指针
}

3,引用 &(在子函数的局部变量中——一般不行,这里分析错误)

#include <stdio.h>
using namespace std;
int x = 100;
int  &f()
{
	//int x = 100;  不能返回局部变量的引用,函数结束后,栈释放空间。什么意思??变量a引用函数f();函数f()又引用局部变量x的值,函数调用开始时为x开辟4个字节里边存放100,调用结束后,栈释放空间,  而变量a的引用需要在整个程序开始直到结束,故需要定义一个全局变量x;
	return x;
}
int main()
{
	int &a =f();
	return 0;
}

4,引用 & (在子函数的形参中)

#include <iostream>
#include <cstrlib>
using namespace std;
void Init(char *&ptr)			//引用,在C中怕是得用二级指针来承接了
{
	ptr = (char *)malloc(sizeof(char));	//在C中(*ptr)=...
}
int main()
{
	char *str = NULL;
	Init(str);				//在C中Init(&str);
	strcpy(str,"helloworld");
	cout << str << endl;
}

5,引用 & (常/变量)

#include <iostream>
using namespace std;
int main()
{
	int a = 1;
	int &b = a;		//普通引用,变量初始化普通引用
	//int &c = 100;	//不能用常量初始化普通引用
	
	
	const int &d = a;		//变量a初始化常引用
	//d++;			//常引用不能被修改

	const int &e = 100;//常量100初始化常引用,编译分配4个字节大小的内存并用100来填充
	//e++;		//常引用不能被修改
	return 0;
}

6,默认参数

#include <iostream>
using namespace std;
void f(int a, int b=100, int c=200)		//一旦使用默认参数,从这个默认参数开始后边所有参数都使用默认参数
{
	cout << a << b << c <<endl;
}
int main()
{
	f(1,2);
	return 0 ;
}

7,占位参数

#include <iostream>
using namespace std;
void f(int a,int b,int =0)		//默认参数与占位参数结合使用
{
	cout << a << b <<endl;
}
int main()
{
	f(1,2);
	return 0 ;
}

8,函数重载
函数重载的标准:
1,形参类型不同
2,形参顺序不同
3,形参个数不同,三个条件满足其一即可
函数返回值不作为函数重载的标准

#include <iostream>
using namespace std;
int f(int i,int j)			//函数类型不同
{
}
float f(float i,float j)
{
}
void f(char a,int b)		//函数顺序不同
{
}
void f(int b,char a)
{
}
/*float f(int i,int j)
{
} */	//函数返回值不同不作为函数重载的标准
int main()
{
	int a =1;b=2;
	float x=1.11,y=2.22
	add(a,b);
	add(x,y);
}

9,函数重载和函数指针

#include <iostream>
using namespace std;
void f(int a,int b
{
	cout << "helloworld" << endl;
}
void f(int a,int b,int c)
{
	cout << "verygood" <<endl;
}
int main()
{
	void (*p) (int ,int );
	p =f;
	p(1,2);
	//p(1,2,3);		//指针为俩参数
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值