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

c++将引用作为函数的参数---6

时间:2016-08-02 01:14:33      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:

原创博客:转载请标明出处:http://www.cnblogs.com/zxouxuewei/

 

引用经常被用作函数参数,使得函数中的变量名成为调用程序中的变量别名。这种传递参数 的方法称为按引用传递。按引用传递允许被调用的函数能够访问调用函数中的变量。C++新增这项特性是对C语言的超越,C语言只能按值传递。按值传递导致被 调用函数使用调用程序的值得拷贝。当然,C语言也允许避开按值传递的限制,采用按指针传递的方式。


代码:

        #include <stdio.h>    
        #include <iostream>  
          
        using namespace std;  
          
        void TestAddress1(int p, int& a, int b)  
        {  
            cout << "TestAddress1" << endl;  
            cout << "p address:" << &p << "; p value:" << p << endl;  
            cout << "a address:" << &a << "; a value:" << a << endl;  
            cout << "b address:" << &b << "; b value:" << b << endl;  
          
            int* c = &b;  
            c -= 2;  
            cout << "c address:" << c << "; c value:" << *c << endl;  
        }  
          
        void TestAddress2(int* a, int b)  
        {  
            cout << "TestAddress2" << endl;  
            cout << "a address:" << &a << "; a value:" << *a << endl;  
            cout << "b address:" << &b << "; b value:" << b << endl;  
        }  
          
        int main()  
        {  
            int* a = new int[5];  
            memset(a, 0, sizeof(int)* 5);  
            a[0] = 123;  
            int b = 2;  
            int c = 3;  
          
            cout << "out a address:" << &a << endl;  
            cout << "out b address:" << &b << endl;  
            cout << "out c address:" << &c << endl;  
          
            cout << "-----------------" << endl;  
          
            TestAddress1(b, b, c);  
          
            cout << "-----------------" << endl;  
          
            TestAddress2(a, b);  
        }

 

c++将引用作为函数的参数---6

标签:

原文地址:http://www.cnblogs.com/zxouxuewei/p/5727781.html

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