C++之引用

来源:互联网 发布:去人声软件 编辑:程序博客网 时间:2024/06/05 07:38

引用

  • 普通变量引用
  • 结构体类型引用
  • 指针类型引用
  • 引用做函数参数
  • 引用和指针的区别

变量类型引用

#include <iostream>using namespace std;int main(void){    int a = 5;    int &b = a; //引用必须初始化    b = 10;    cout << a << endl; //10     return 0;}

结构体类型引用

#include <iostream>using namespace std;typedef struct{    int x;    int y;}Coor;int main(void){    Coor c1;    Coor &c = c1;    c.x = 5;    c.y = 10;    cout << c1.x << c1.y << endl;// 5 10    return 0;}

指针类型引用

using namespace std;int main(void){    int a = 5;    int *p = &a;     int *&q = p; //引用必须初始化    *q = 10;    cout << a << endl; //10    system("pause");    return 0;}

引用做函数参数

#include <iostream>using namespace std;void fun(int &a,int &b){    int c = 0;    c = a;    a = b;    b = c;}int main(void){    int x = 5, y = 21;    cout << "x = " << x << endl; //5    cout << "y = " << y << endl; //10    fun(x, y);    cout << "x = " << x << endl; //10    cout << "y = " << y << endl; //5    system("pause");    return 0;}

引用和指针的区别

待补充

0 0
原创粉丝点击