-1

我正在学习 C++ 的参考,并尝试了 Thinking in C++ 中的以下代码:

但是,我发现如果我没有将引用转换为 'long' 类型,则fg的引用是相同的,我认为这没有意义,并且它们的值都是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
4

2 回答 2

3

因为ostream有 for 的重载,operator<<并且void*任何数据指针都可以转换为,所以打印s likevoid*的地址。但是,函数指针不能转换为,所以这个特殊的重载是不合适的。intjvoid*

那是另一个operator<<重载开始发挥作用的时候,在这种情况下,它将是bool. 函数指针可以转换为bool(true == 指针为非 NULL)。指向的指针f非 NULL,因此在此转换中它产生 true,打印为 1。

于 2012-04-25T18:05:50.827 回答
1

这与引用无关。该程序不使用任何引用。您正在使用 address-of 运算符&。见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
于 2012-04-25T18:03:00.917 回答