C++练习4

引用的本质就是给同一个内存空间起不同的名字

#include <iostream>

using namespace std;

int main()
{
    int a =10;
    int &b = a;
    b =20;     //通过引用变量b和a指向同一个内存,改变b的值 就能够改变a的值   在这里虽然只是对b进行赋值
//  printf("a = %d\n",a);
   cout << "a = " << dec <<  a <<endl;
   cout << "b = " << hex << b << endl;           

    system("pause");      
    return 0;
}

引用必须要进行初始化

#include <iostream>

using namespace std;

//引用的基本基本知识

void mySwap(int *a ,int* b)
{
//在swap函数中要使用指针进行值的交换定义一个指针的时候必须顶一个变量这样能够防止没有初始化的指针会随意指向存放系统参数的内存地址,要是不进行初始化很可能会替换掉系统中重要的参数而导致不可预知的情况发生
      int *c, d;
      c = &d;
      *c = *a;
      *a = *b;
      *b = *c;
}

int main()
{
    int x,y;
    x = 10;
    y = 20;
    mySwap(&x,&y);
    cout << "x =" << x << "y =" << y <<endl;



    system("pause");      
    return 0;
}

猜你喜欢

转载自blog.csdn.net/andrewgithub/article/details/78605974