设为首页 加入收藏

TOP

【2】学习C++之引用
2019-04-06 20:09:20 】 浏览:94
Tags:学习 引用

C++中的引用类似于现实生活中人们之间起昵称,昵称和本名都可以辨别人。

1.普通变量的引用:

int a=10;//a为本名
int &b=a;//b为a的昵称

其中不能光有昵称没有本名,如果只定义了引用,却没有将这个引用指向哪个变量,编译器会报错。

2.结构体的引用:

typedef struct 
{
    int x;
    int y;
}Coor;

#include <iostream>
using namespace std;
int main(void)
{
    Coor c1;
    Coor &c=c1;
    c.x=10;
    c.y=20;
    cout<<c1.x<<c1.y;//使用引用也能输出c的值
    return 0;
}

3.指针类型的引用:

一般形式为——类型 *&指针引用名 = 指针;

#include <iostream>
using namespace std;
int main(void)
{
    int a = 10;
    int *p = &a;
    int *&q = p;
    *q = 20;
    cout << a << endl;
    return 0;
}

4.引用作为函数参数:

两种函数参数对比:

第一种:

void fun(int *a,int *b)
{
    int c = 0;
    c = *a;
    *a = *b;
    *b = c;
}

int x = 10,y = 20;
fun(&x,&y);

第二种:

void fun(int &a,int &b)
{
    int c = 0;
    c = a;
    a = b;
    b = c;
}

int x = 10,y = 20;
fun(x,y);

 

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇#leetcode刷题之路45-跳跃游戏 II 下一篇NLPIR(北理工张华平版中文分词系..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目