c++引用/参数/动态空间管理

2-7引用的声明及访问示例

#include<iostream>
using namespace std;
int x = 5, y = 10;
int &r = x;//声明一个引用r作为变量x的别名
void print()
{
	cout << "x=" << x << "y=" << y << "r=" << r << endl;
	cout << "Address of x" << &x << endl;//输出变量x的内存地址
	cout << "Addreas of y" << &y << endl;//输出变量y的内存地址
	cout << "Addreas of r" << &r << endl;//输出变量r的内存地址

}
int main()
{
	print();//第一次调用输出函数
	r = y;//相当于x=100,将y的值赋给x,而不是将r改为变量y的别名
	print();//第二次调用输出函数,x,y,r的值相同
	y = 100;//对y重新赋值
	x = y - 10;//x和r同时改变
	print();//第三次调用输出函数
	return 0;
}

2-8引用参数修改对应实际参数变量的值

#include<iostream>
using namespace std;
void swap(int& x, int& y)
{              //引用参数成为对应实际参数变量的别名
	int t = x;//通过3条赋值语句交换x和y的值
	x = y;
	y = t;
}
int main()
{
	int a = 3, b = 5, c = 10, d = 20;
	cout << "a=" << a << " b=" << b << endl;//输出交换前的a,b的值
	swap(a, b);//调用函数,参数传递相当于执行了int &x=a;int &y=b;使引用参数获得了初值

	cout << "a=" << a << " b=" << b << endl;//输出交换后的a、b值
	cout << "c=" << a << " d=" << d << endl;//输出交换前的c、d值
	swap(c, d);//调用函数,参数传递相当于执行了int &x=c;int &y=d;使引用参数获得了初值

	cout << "c=" << c << " d=" << d << endl;//输出交换后的c、d值
	return 0;
}   

2-9 参数使用示例

#include<iostream>
using namespace std;
int Fun(const int &x, int &y, int z)//const修饰符使其成为常引用
{
	//x++;//此句若作为函数的语句,则报错:“不能给常量赋值”
	y++;//通过修改y改变第2个实际参数变量的值
	z++;//对z的修改不会影响对应的实际参数变量
	return y;
}
int main()
{
	int a = 1, b = 2, c = 3, d = 0;
	cout << "a=" << a << " b=" << b << " c=" << c << " d=" << d << endl;
	d = Fun(a, b, c);//实际参数a和c都不能被修改,b被修改了
	cout << "a=" << a << " b=" << b << " c=" << c << " d=" << d << endl;
	return 0;
}

2-10动态空间管理示例

#include<iostream>
#include<iomanip>
#include<cmath>
#include<ctime>
using namespace std;
const int N = 30;
int main()
{
	int* p, * sum, i;
	sum = new int(0);
	p = new int[N];
	if (p == NULL)
	{
		cout << "allocation failure.\n";
		return 0;
	}
	srand(time(NULL));
	for (i = 0;i < N;i++)
	{
		p[i] = rand() % 100;
		if (p[i] % 2)
			(*sum)++;

	}
	for (i = 0;i < N;i++)
	{
		cout << setw(4) << p[i];
		if ((i + 1) % 10 == 0)
			cout << endl;
	}
	cout << "the number of odd is:" << *sum << endl;
	delete []p;
	delete sum;
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

` starmultiple `

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值