簡體   English   中英

C++和Python的參數區別

[英]parameter difference between C++ and Python

C++

#include <iostream>

using namespace std;

void doSomething(int y)  
{             
    cout << y << " "<< & y << endl; 

}

int main()
{
    
    int x(0);
    cout << x << " " << & x << endl; 
    doSomething(x); 
    return 0;
}

Python

def doSomething(y):
    
    print(y, id(y))

x = 0

print(x, id(x))

doSomething(x)

我認為他們的代碼應該返回相同的結果但是 C++ 結果是

0 00000016C3F5FB14

0 00000016C3F5FAF0

Python結果是

0 1676853313744

0 1676853313744

我不明白為什么變量的地址在 Python 中沒有改變,而變量的地址在 C++ 中改變了

我不明白為什么變量的地址在 Python 中沒有改變,而變量的地址在 C++ 中改變了。

因為在 python 中,我們傳遞的是對象引用而不是實際的對象。

在您的 C++ 程序中,我們通過 value傳遞x 這意味着函數doSomething具有傳遞的參數的單獨副本,並且由於它具有單獨的副本,因此它們的地址與預期的不同。


可以使 C++ 程序產生與 python 程序等效的輸出,如下所述。 演示

如果您將doSomething的函數聲明更改為void doSomething(int& y)您將看到現在您得到與 python 相同的結果。 在下面修改后的程序中,我將參數更改為int&而不僅僅是int

//------------------v---->pass object by reference
void doSomething(int& y)  
{             
    cout << y << " "<< & y << endl; 

}

int main()
{
    
    int x(0);
    cout << x << " " << & x << endl; 
    doSomething(x); 
    return 0;
}

上述修改程序的輸出等價於python產生的輸出:

0 0x7ffce169c814
0 0x7ffce169c814

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM