码迷,mamicode.com
首页 > 编程语言 > 详细

C++学习记录(1)——引用

时间:2015-04-30 21:32:28      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:

#include <iostream>
#include <stdlib.h>

using namespace std;
/*通过此程序可以发现引用的引用变了,原来的值还是会变,
 *所以定义函数的时候,如果想让实际变量发生变化,形式
 *参数可以定义成引用的形式。另外要注意的是,这里的&不
 *是C中的取地址符号,而是引用的意思。
 */ 
int main(int argc, char** argv)
{
    
    //定义两个变量 
    int x = 100;
    int y = 200;
    //为两个变量建立引用 
    int &x1 = x;    
    int &y1 = y;
    //为引用再次建立引用
    int &x2 = x1;
    int &y2 = y1; 

    cout<<"交换变量前:"<<endl; 
    cout<<x<<","<<y<<endl;
    
    swap(x,y);
    cout<<"swap(x,y)"<<endl; 
    cout<<x<<","<<y<<endl;
    
    swap(x1,y1);
    cout<<"swap(x1,y1)"<<endl; 
    cout<<x<<","<<y<<endl;
    
    swap(x2,y2);
    cout<<"swap(x2,y2)"<<endl; 
    cout<<x<<","<<y<<endl;
    system("pause");
}
//通过引用来交换两个变量 
void swap(int &x,int &y) {
    int temp;
    temp = x;
    x = y;
    y = temp;
}
#include <stdlib.h>
#include <iostream>
/*指针的引用为了不被弄晕,可以把int *p写成int* p,这样把int*看成一个数据类型, 
 *接下来要创建引用则在int*后面后变量名前面加上&就OK了 
 */
using namespace std;

int main(int argc, char** argv)
{
    int x = 100;
    int* p = &x;
    int* &q = p;
    cout<<q<<endl;
    
    return 0;
}

 

C++学习记录(1)——引用

标签:

原文地址:http://www.cnblogs.com/Junely/p/4469708.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!