#include<iostream>
#include<string>
using namespace std;
//内联函数:使用函数代码替换函数调用---一般只用在函数内容简单的时候,节省时间
inline double square(double x) {return x * x; }
//标志:在函数声明前或定义前加上关键字inline
void swap_y(int & a ,int & b);
void swap_p(int * x ,int * y);
void swap_s(int p,int q);
int main()
{
double a,b;
a = square(5.3);
b = square(5.5 + 6.5);
cout << "a = " << a << endl;
cout << "b = " << b << endl;
//引用:就是给已经定义的变量起个别名---必须在声明引用时进行初始化
int contemplative = 666;
int & charitable = contemplative;//&这个符号是来声明引用的;int &---指向int的引用
//contemplative和charitable指向的是相同的值和内存单元
cout << "contemplative = " << contemplative << endl;
cout << "charitable = " << charitable << endl;
contemplative++;
cout << "contemplative = " << contemplative << endl;
cout << "charitable = " << charitable << endl;//他们指向的值是一样的
cout << "Address : charitable : " << &charitable << endl;
cout << "Address : contemplative : " << &contemplative << endl; //他们指向的内存空间也是一样的
int frank = 88;
charitable = frank;//这条语句相当于contemplative = frank;
cout << "frank : " << frank << endl;
cout << "charitable : " << charitable << endl;
cout << "contemplative = " << contemplative << endl;//可以看出他们的值都是88,都是一样的
//可以通过初始化声明来设置引用,但不能通过赋值来设置
cout << "Address : frank : " << &frank << endl;
cout << "Address : chartitable " << &charitable << endl;//因为他们的地址是不一样的
//将引用用作函数参数
int passionate = 999,painstaking = 888;
cout << "Value : passionate -> " << passionate;
cout << " Value : painstaking -> " << painstaking << endl;
swap_y(passionate,painstaking);
cout << "Value : passionate -> " << passionate << " Value : painstaking -> " << painstaking << endl;
swap_p(&passionate,&painstaking);
cout << "Value : passionate -> " << passionate << " Value : painstaking -> " << painstaking << endl;
swap_s(passionate,painstaking);
cout << "Value : passinonate -> " << passionate << " Value : painstaking -> " << painstaking << endl;
//临时变量--如果引用参数是const,生成临时变量。条件:①实参的类型正确,但不是左值;②实参的类型不正确,但可以转换成正确的类型
//左值--可以取地址,可以保存数据的,可以放在‘=’的左边或右边(例如:变量、数组元素、结构成员、引用、解除引用的指针)--使用&声明的引用
//右值--不可取地址,数据,只能出现在‘=’的右边(例如:字符常量、函数的返回值)--使用&&声明的引用
int &a = 2;//× 左值引用绑定到右值
int b = 2;//非常量左值
const int &c = b;//√ 常量左值引用绑定到非常量左值
const int d = 2;//常量左值
const int &e = c;//√ 常量左值引用绑定到常量左值
const int &b = 2;//√ 常量左值引用绑定到右值
int q;
int &&p1 = q;//× 右值引用不能绑定到任何左值
int &&p2 = std::move(q);//√ 通常可以用std::move来将左值强制转换成右值
return 0;
}
//按引用传递
void swap_y(int &a,int &b)//a,b相当于时passionate和painstaking的别名,交换a,b的值相当于交换passionate和painstaking的值
{
int temp;
temp = a;
a = b;
b = temp;
}
//按地址传递
void swap_p(int *x,int *y)//x,y是通过指针按地址传递了passionate和painstaking的值,需要使用解除引用运算符*,来访问变量的值
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
//按值传递
void swap_s(int p,int q)//p,q是复制了passionate和painstaking的新变量,并不会影响passionate,painstaking的值
{
int temp;
temp = p;
p = q;
q = temp;
}