1. 引用&、指针*、存储空间new的使用
// 说明:引用的使用 &, 指针* 和new 存储空间的使用
//
#include <iostream>
using namespace std;
void func(int bb, int &cc, int *ptrD)
{
bb = 5;
cc = 6;
*ptrD = 7;
}
int main()
{
//申请动态变量 指针*和new
int *ptr1 = new int(3);
std::cout << "Hello World!\n";
double *ptr2;
ptr2 = new double(3.2);
double *ptr3 = new double;
cout << *ptr1 << '\t' << *ptr2 << '\t' << *ptr3 << endl;
delete ptr1; //不使用时及时清空动态变量和动态数组
delete ptr2;
delete ptr3;
//申请动态数组
int n;
cin >> n;
double *ptr4 = new double[n];
ptr4[2] = 3;
cout << *(ptr4 + 2)<<endl;
delete[]ptr4;
// 引用 &
int a = 1, &b = a, c(2), d(3);
cout << "a=" << a << ",b=" << b << endl;
b = 4;
cout << "a=" << a << ",b=" << b << endl;
func(b, c, &d);
cout << "a=" << a << ",b=" << b << ",c=" <<c<< ",d=" << d << endl;
}
运行结果如下:
Hello World!
3 3.2 1.61324e-307
4
3
a=1,b=1
a=4,b=4
a=4,b=4,c=6,d=7