我正在学习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
答案 0 :(得分:3)
由于ostream
operator<<
的重载次数为void*
而且任何数据指针都可以转换为void*
,int
的地址1}}像j
一样打印出来。但是,函数指针无法转换为void*
,因此这种特殊的重载已经过时了。
当另一个operator<<
重载发挥作用时,在这种情况下,它将是bool
的重载。函数指针可以转换为bool
(true ==指针为非NULL)。指向f
的指针为非NULL,因此在此转换中产生true,打印为1。
答案 1 :(得分: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