2017-08-26 113 views
3

我不明白爲什麼我不能打印指針的地址。我知道理解指針是非常重要的,所以任何幫助都是值得讚賞的。傳遞函數指針 - 爲什麼我不能打印地址?

void printp(int& test) 
{ 
     cout << test << endl; 
} 

int main() 
{ 
     int *p = new int; 
     *p = 1; 
     int np = 0; 

//  printp(p); // why doesn't this print the address of p? 
//  printp(&p); // why doesn't this print the address of p? 
     printp(*p); // prints 1 
     printp(np); // prints 0 

return 0; 
} 

當我嘗試使用'printp(p)'時,出現以下錯誤。

test.cpp: In function ‘int main()’: 
test.cpp:17:10: error: invalid conversion from ‘int*’ to ‘int’ [-fpermissive] 
    printp(p); // why doesn't this print the address of p? 
     ^
test.cpp:5:6: note: initializing argument 1 of ‘void printp(int&)’ 
void printp(int& test) 
     ^~~~~~ 
test.cpp:17:10: error: cannot bind rvalue ‘(int)p’ to ‘int&’ 
    printp(p); // why doesn't this print the address of p? 
+6

'INT&test'是一個參考,不一個指針。 –

+0

只有一個猜測,但我認爲printp不能輸出一個int * ..你可以嘗試先將p轉換爲int,然後再轉換成輸出。 – derHugo

+0

只有一個猜測,但我認爲printp不能輸出一個int * ..你可以嘗試先將p轉換爲int,然後再轉換爲輸出。 – derHugo

回答

8

由於編譯器需要參考參數的確切類型,因此您會收到來自編譯器的錯誤消息。

當一個函數具有基準參數

void printp(int& test); 

代替指針參數,

void printp(int* test); 

調用者必須提供的確切類型的變量。它不能提供對任何其他類型變量的引用(除了dynamic_cast從其他類型到參數類型時)。

所以,當你調用printp(p);,編譯器要求p是類型int,不int *的。

如果按值傳遞,編譯器會促進或部分的static_cast類型你,

void printp(int test); 
short s = 0; 
printp(s); // s is promoted to int here. 

但是編譯器不能爲你做的,當參數是一個參考。

2

在你的代碼printp(int&)是一個函數,它的引用沒有指針,以便得到指針的地址,你的情況,你可以簡單地改變它或超載它:

void printp(int* test){ 
    cout << test << endl; // the addres test contains not its address 
    cout << &test << endl; // the address of test itself 
    cout << *test << endl; // the value in the address that test points to 
} 

在主:

printp(p); 

輸出:

00893250 
0018FEEC 
1 
2

對於int a;

expr | type 
-----+----- 
&a | int* 
a | int 
*a | - (not valid) 

int* p;

expr | type 
-------+----- 
&p | int** 
p | int* 
*p | int 
**p | - (not valid) 

int** pp;

expr | type 
-------+----- 
&pp | int*** 
pp | int** 
*pp | int* 
**pp | int 
***pp | - (not valid) 
0

INT &是指向int不是指針的引用。您需要更改的功能定義:

void printp(int* test) 
{ 
    cout << test << endl; 
} 

然後在main()

printp(p); 
printp(&np); 

這將輸出類似:

0x55847f523c20 
0x7ffffc7fb07c