C++與Java,C#的異同(一):值,地址,引用

Java,C#已經比較熟悉,最近在從0開始自學C++。學習過程當中必然會與Java,C#進行對比,有吐槽,也有點贊。java

先來說講最基本也是最重要的部分:參數傳遞的方式。函數

對於類型, Java分基本類型、複合類型,從另一個角度分是值類型,引用類型。在展開對比前, 咱們先來看看三個關鍵方式:學習

  • spa

    • 建立新的副本,與原來的沒有關係
  • 地址(指針)指針

    • 把對象所在內存的地址傳遞過去
  • 引用code

    • 能夠理解爲變量的別名

舉個例子:對象

 1 void testMethodA(int input) {
 2     input = 999;
 3 }
 4 
 5 void testMethodB(int* input) {
 6     //int newValue = 888;
 7     *input = 888;
 8 }
 9 
10 void testMethodC(int& input) {
11     input = 777;
12 }
13 
14 int main() {
15 
16     int input = 111;
17     cout << "Original: " << input << endl;
18     testMethodA(input);
19     cout << "After testMethodA: " << input << endl;
20     cout << input;
21     testMethodB(&input);
22     cout << "After testMethodB: " << input << endl;
23     cout << input;
24     testMethodC(input);
25     cout << "After testMethodC: " << input << endl;
26 
27     std::cin.get();
28 
29     // What is the value of input?
30 
31 }

運行後的結果:blog

Original: 111
After testMethodA: 111
111After testMethodB: 888
888After testMethodC: 777

 

 解釋一下:內存

函數 testMethodA 的參數是值傳遞的,調用函數後,建立了一個input的副本,副本的值改變了, 可是input值沒有被改變。ci

函數 testMethodB 的參數是地址(指針)傳遞的,函數內修改了input指向的那塊內存區域,因此input的值也被改變了。

函數 testMethodC的行爲看起來是和函數 testMethodB是同樣的, input值也被改變了,他們有什麼區別呢?

區別在於:

傳遞地址,函數內改變的是變量指向的那塊內存區域的內容。

傳遞引用,函數內改變的是變量的指向,換句話說,input指向的內存地址都變了。

 以下圖:

在C++裏面,全部的類型,無論是基礎數據類型,結構體,仍是類,默認都是「值」傳遞的;顯式聲明爲指針,纔是傳地址;顯式聲明爲引用,能夠認爲就是給變量起了一個別名。

在Java裏面,只有基礎數據類型(int, double, float等),是值傳遞的,全部的類對象,都是傳地址(注意,不是傳引用), 實際上,java裏面沒有引用傳遞的概念。

在C#裏面, 基礎數據類型,結構體, 默認都是值傳遞;全部的對象, 默認都是傳地址;若是想傳引用,在參數前面加ref關鍵字,例如:

1  void testMethodC(ref int input) {
2      input = 777;
3  }
相關文章
相關標籤/搜索