2015-04-19 47 views
0

你能告訴我來源1和2之間的區別嗎?這本書說第一個是按地址(指針)調用,第二個是按引用調用,但我不完全得到這兩個來源。 請給我解釋這些消息,請提前謝謝。通過地址(指針)和通過引用呼叫之間的區別

1.

#include <iostream> 
using namespace std; 

void absolute(int *a); 
void main() 
{ 
    int a = -10; 
    cout << "Value a before calling the main function = " << a << endl; 
    absolute(&a); 
    cout << "Value a after calling the main function = " << a << endl; 
} 
void absolute(int *a) 
{ 
    if (*a < 0) 
     *a = -*a; 
} 

2.

#include <iostream> 
using namespace std; 

void absolute(int &a); 
void main() 
{ 
    int a = -10; 
    cout << "Value a before calling the main function" << a << endl; 
    absolute(a); 
    cout << "Value a after calling the main function" << a << endl; 
} 
void absolute(int &a) 
{ 
    if (a < 0) 
     a = -a; 
} 
+0

你也可以參考http://www.cplusplus.com/articles/ENywvCM9/ – chenzhongpu

回答

0

在CPU級別會發生什麼情況而言,指針和引用是完全一樣的。不同之處在於編譯器,它不會讓你在參考上做一個刪除操作(並且輸入的數量更少)

所以在你的代碼中,兩個函數都做同樣的事情。