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;
}