c++將引用作為函數的參數---6


原創博客:轉載請標明出處: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);  
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM