[英]pointer argument receiving address in c++?
int y=5;
int *yPtr = nullptr;
yPtr = &y;
我知道指針存儲y的地址。 並調用* yPtr取消引用y。
如果我調用了void函數:
int main()
{
int number = 5;
function( &number );
}
void function( int *nPtr)
{
*nPtr = *nPtr * *nPtr;
}
如果函數以指針作為參數,對函數的調用如何使用地址? 我知道nPtr存儲地址,但為什么不能將其定義為。
void functions (int &ref)
{
ref = ref * ref;
}
我的主要問題是:為什么接收地址參數的函數需要指針參數來接收地址?
通過使用傳遞引用參數,您可以強制函數不復制參數本身的值,而是使用您提供的實際變量。 因此,對於更清晰的視圖,請參見下文:
void function( int number )
{
cout << number;
}
function( myInt ); // function will copy myInt, into its local variables stack
但是,通過使用按引用傳遞方法,如下所示:
void function ( int & number )
{
cout << number
}
function( myInt ); // function will not copy myInt into its local variables stack, instead, it will use the already existent myInt variable.
編譯器如何使用傳遞指針和傳遞引用參數沒有什么區別。 相反,函數的調用將如下所示:
void function_p( int *number )
{
cout << *number;
}
void function_r( int & number )
{
cout << number;
}
// and the calls
function_p( &myInt ); // it is required to use address-of operator here
function_r( myInt ); // the effect will be the same, but with less effort in writing that address-of operator
通常,在C ++ 11中,程序員開始使用按引用傳遞方法,通常是因為它更容易編寫“模板”。
為了完成對問題的解答, *
和&
運算符僅引用參數的類型,以便它們創建復合類型。 復合類型是根據另一種類型定義的類型。 C ++有幾種復合類型,其中兩種是引用和指針。
您可以理解,通過以適當的方式編寫變量,它們只會影響變量的類型(在我們的示例中為參數):
int* p1; // we will read this: pointer p1 points to an int
int* p2 = &var1; // we read this: pointer p2 points to int variable var1
int var1 = 12;
int& ref1 = var1; // and we read this: ref1 is a reference to var1
通常,您可以考慮在同一塊內存中引用代表不同的引用。
你的意思是
void functions (int &ref)
{
ref = ref * ref;
}
這就是使用引用的方式,避免了指針語法的所有“ *”
這是C ++那些古怪的東西。 通過引用傳遞與傳遞指針不同。 當你做類似的事情
void functions (int &ref)
您可以將實際變量傳遞給functions
(而不是指向它們的指針),例如
int a = 12;
functions(a);
在函數內部,您無需取消引用。 請注意,您是通過引用傳遞,而不是傳遞一個參考。
當您傳遞參考或指向某物的指針時,您可以像這樣使用星號
void function( int *nPtr)
因此,您必須使用*取消引用
還要注意,您可以通過在變量(或常量)前加上&
來獲得對變量(或常量)的引用,但可以在變量(或常量)前加*
來聲明引用或指針。 同時,還可以通過在指針前面加*
來取消引用指針。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.