C++基础知识(引用)

C++的特点

  1. C语言基础上,支持面向对象开发
  2. 功能强大,应用领域广泛
  3. 为数不多可以底层开发的面向对象语言,开发系统软件
  4. 在面向对象语言开发效率高
    关键字:
    对象,强大,底层,效率

C到C++

C语言面向过程

核心:该怎么做

C++面向对象

核心:让谁来做

这里就可以知道C++处理事情更加高效和方便

面向对象还有三大特性:封装、继承、多态

引用(&)

引用是给变量取别名,操作引用就相当于操作引用本身(不会开辟新的空间)

#include <iostream>
using namespace std;
int main()
{
  int jiNan=90;
  int &quanCheng=jiNan;		//取别名
  quanCheng+=5;
  //cout是输出  endl:end line 换行
  cout<<quanCheng<<" "<<jiNan<<endl; //95 95
  cout<<&quanCheng<<" "<<&jiNan<<endl; //0x61fe88 0x61fe88
}

引用的性质

当成为一个变量的引用后,就不能成为其他变量的引用

#include <iostream>
using namespace std;
int main()
{
  int jiNan=90;
  int qingDao=91;
  int &quanCheng=jiNan;
  //&quanCheng=qingDao;//错误 不能重新赋值
}

引用必须有初值,并且不能成为NULL

#include <iostream>
using namespace std;
int main()
{
  int jiNan=90;
  int qingDao=91;
  //int &quanCheng; //错误必须赋值
  //int &quanCheng=NULL;//不能赋值NULL
}
//引用的本质是指针常量  int * const b=&a;

如果初始化的初值是纯数字,引用需要定义为常引用(代表引用不能修改所指向的内用)

#include <iostream>
using namespace std;
int main()
{
  //引用是可读可写  100只是可读
  //int &b=100; 错误
    const int & b=100;
    cout<<b<<endl;
}

如果引用定义成常引用,就不能直接更爱变量的值,但是可以通过变量间接更改引用的值

#include <iostream>
using namespace std;
int main()
{
  int a=100;
  const int & b=a;
  cout<<a<<" "<<b<<endl; //100 100
  //b++; error: increment of read-only reference 'b'
  a++;
  cout<<a<<" "<<b<<endl; //101 101
}

引用的应用

引用作为参数,不需要给参数开辟空间,也没有产生副本,提高了效率

#include <iostream>
using namespace std;
void test(int a,int b){
   int t=a;
   a=b;
   b=t;
}
void test2(int * a,int * b){
  int t=*a;
  *a=*b;
  *b=t;
}
void test3(int & n,int & m){
    int t;
    t=n;
    n=m;
    m=t;
}
int main()
{
    int n=10;
    int m=20;
    test2(&n,&m);
    cout<<n<<" "<<m<<endl; //20 10
    test3(n,m);
    cout<<n<<" "<<m<<endl;  //10 20
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值