引言
C++包含了C语言的全部语法,任何合法的C语言程序,都是合法的C++程序
C++还在C的基础上做了很多扩展,主要是为了实现面向对象编程和泛型编程
不过既然是第一章,先讲些和面向对象以及泛型关系不太大的扩展
引用的概念
#include<iostream>
using namespace std;
int main(void)
{
int n=4;
int &r=n;
r=4;
cout<<n<<endl;//4
n=5;
cout<<r<<endl;//5
return 0;
}
引用的性质
#include<bits/stdc++.h>
//这是C++万能头文件,包含了目前C++所有核心头文件,包括
/*#include <iostream>
#include <cstdio>
#include <fstream>
#include <algorithm>
#include <cmath>
#include <deque>
#include <vector>
#include <queue>
#include <string>
#include <cstring>
#include <map>
#include <stack>
#include <set>*/
using namespace std;
int main(void)
{
double a=4,b=5;
double &r1=a;
double &r2=r1;//r2也引用a
r2=10;
cout<<a<<endl;//10
r1=b;//r1没有引用b,这里仅仅进行赋值操作
cout<<a<<endl;//5
return 0;
}
引用的应用
1.作为函数形参,在函数中修改外部变量的值(类似于指针)
#include<bits/stdc++.h>
using namespace std;
void valueExchange(int&,int&);
int main(void)
{
int a=4,b=5;
valueExchange(a,b);
cout<<a<<endl;//5
cout<<b<<endl;//4
return 0;
}
void valueExchange(int &x,int &y)
{
int temp;
temp=x;
x=y;
y=temp;
return;
}
2.作为函数返回值
#include<bits/stdc++.h>
using namespace std;
int n=5;
int &setValue()
{
return n;
}
int main(void)
{
setValue()=40;
cout<<n;//40
return 0;
}
常引用
常引用和非常引用的转换
#include<bits/stdc++.h>
using namespace std;
int main(void)
{
int n=5;
int &r1=n;
const int &r=r1;
cout<<r;//编译通过,输出5
return 0;
}
#include<bits/stdc++.h>
using namespace std;
int main(void)
{
int n=5;
const int &r1=n;
int &r=r1;//编译错误
cout<<r;
return 0;
}