![](/img/trans.png)
[英]C++: Why does my function return a reference address different from the dereferenced pointer's address?
[英]why does the value of the function's “address” is 1 in C++?
我正在學習有關C ++的參考,並且嘗試了“ Thinking in C ++”中的以下代碼:
但是,我發現如果不將引用強制轉換為“ long”類型,則f和g的引用是相同的,我認為這是沒有意義的,它們的值都為1,而不是顯示為十六進制,有人可以解釋嗎?
謝謝。
include <iostream>
using namespace std;
int dog, cat, bird, fish;
void f(int pet) {
cout << "pet id number:" << pet << endl;
}
void g(int pet) {
cout << "pet id number:" << pet << endl;
}
int main() {
int i,j, k;
cout << "f() normal: " << &f << endl;
cout << "f() long: " << (long)&f << endl;
cout << "g() normal: " << &g << endl;
cout << "g() long: " << (long)&g << endl;
cout << "j normal: " << &j << endl;
cout << "j long: " << (long)&j << endl;
cout << "k: " << (long)&k << endl;
k=2;
cout << "k: " << (long)&k << endl;
} //
結果
f() normal: 1
f() long: 4375104512
g() normal: 1
g() long: 4375104608
j normal: 0x7fff6486b9c0
j long: 140734879939008
k: 140734879939004
k: 140734879939004
因為ostream
對於void*
具有operator<<
的重載,並且任何數據指針都可以轉換為void*
,所以將打印int
s的地址,如j
。 但是,函數指針不能轉換為void*
,因此這種特殊的重載是無法解決的。
那是當另一個operator<<
重載開始起作用時,在這種情況下,對於bool
來說將是重載。 可以將函數指針轉換為bool
(使用true ==指針為非NULL)。 指向f
的指針是非NULL,因此在此轉換中它會產生true,並顯示為1。
這與引用無關。 該程序不使用任何引用。 您正在使用地址運算符&
。 參見https://stackoverflow.com/a/9637342/365496
f() normal: 1 the address of f is converted to bool 'true' and printed
f() long: 4375104512 the address of f is converted to an integer
g() normal: 1 the address of g is converted to bool 'true' and printed
g() long: 4375104608 the address of g is converted to an integer
j normal: 0x7fff6486b9c0 the address of j is printed directly (there's an operator<< for this but not one for printing function pointers like f and g)
j long: 140734879939008 the address of j is converted to an integer
k: 140734879939004 the address of k is converted to an integer
k: 140734879939004 the address of k is converted to an integer
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.