【题目3-1】一般变量的引用
1 #include <iostream> 2 #include <string> 3 using namespace std; 4 int main(){ 5 int a = 10; 6 int b = 20; 7 int &rn = a; 8 int equal; 9 10 rn = b; 11 cout<<"a="<<a<<endl; //20 12 cout<<"b="<<b<<endl; //20 13 14 rn = 100; 15 cout<<"a="<<a<<endl; //100 16 cout<<"b="<<b<<endl; //20 17 18 equal = (&a==&rn)?1:0; //1 19 cout<<"equal="<<equal<<endl; 20 return 0; 21 }
运行结果如下
a = 20 b = 20 a = 100 b = 20 equal = 1
【题目3-2】指针变量引用
1 #include <iostream> 2 using namespace std; 3 int main(){ 4 int a = 1; 5 int b = 10; 6 int* p = &a; 7 int* &pa = p; 8 9 (*pa)++; 10 cout<<"a="<<a<<endl; //2 11 cout<<"b="<<b<<endl; //10 12 cout<<"*p="<<*p<<endl; //2 13 14 pa = &b; 15 (*pa)++; 16 cout<<"a="<<a<<endl; //2 17 cout<<"b="<<b<<endl; //11 18 cout<<"*p="<<*p<<endl; //11 19 return 0; 20 }
【题目3-3】代码找错 - 变量引用
1 #include <iostream> 2 using namespace std; 3 int main(){ 4 int a = 1,b = 2; 5 int &c; // 引用在声明时要初始化 6 int &d = a; 7 &d = b; // 引用只能在声明的时候被赋值,以后都不能再把该应用作为其他变量名的别名 8 int *p; 9 *p = 5; //p没有被初始化,为野指针,对野指针赋值会导致程序运行时崩溃 10 return 0; 11 }
【知识点】引用在声明时要被初始化,且之后被不能被作为其他变量名的别名
【题目3-4】实现交换两个字符串的功能
1 #include <iostream> 2 using namespace std; 3 void swap(char* &x, char* &y){ 4 char *temp; 5 temp = x; 6 x = y; 7 y = temp; 8 } 9 int main(){ 10 char *ap = "hello"; 11 char *bp = "how are you?"; 12 13 cout<<"*ap":<<ap<<endl; 14 cout<<"*bp:"<<bp<<endl; 15 swap(ap,bp); 16 cout<<"*ap:"<<ap<<endl; 17 cout<<"*bp:">>bp<<endl; 18 return 0; 19 }
运行结果如下
*ap: hello
*bp: how are you?
*ap: how are you?
*bp: hello
【题目3-5】程序查错 - 参数引用
1 #include <iostream> 2 using namespace std; 3 4 const float pi = 3.14f; 5 float f; 6 7 float f1(float r){ 8 f = r * r * pi; 9 return f; 10 } 11 12 float& f2(float r){ 13 f = r * r * pi; 14 return f; 15 } 16 17 int main(){ 18 float f1(float=5); // 声明 f1() 函数默认参数为5 19 float& f2(float=5); // 声明 f2() 函数默认参数为5 20 float a = f1(); // 78.5 21 float& b = f1(); // wrong 22 float c= f2(); // 78.5 23 float& d = f2(); // 78.5 24 d += 1.0f; // 79.5 25 cout<<"a="<<a<<endl; // 78.5 26 cout<<"b="<<b<<endl; // 注释掉 27 cout<<"c="<<c<<endl; // 78.5 28 cout<<"d="<<d<<endl; // 79.5 29 cout<<"f="<<f<<endl; // 79.5 30 return 0; 31 }
Line 18,19 对 f1,f2 函数进行函数默认参数确定
Line 21 发生错误,f1() 返回为临时变量,不能对临时变量建立引用
Line 23 对全局变量 f 进行引用。d 变量的声明周期 小于 f 全局变量的 声明周期,没有问题。但是,若此时将一个局部变量的 引用返回,会出现错误
【知识点】:不能对临时变量建立引用。若错误操作,会产生如下的报错信息
Non-const lvalue reference to type ‘float‘ cannot bind to a temporary of type ‘float‘
C++ 引用 (by-reference variable)
原文:https://www.cnblogs.com/jg01/p/12465379.html