【问题标题】:why does the value of the function's "address" is 1 in C++?为什么函数的“地址”的值在 C++ 中是 1?
【发布时间】:2012-04-25 17:54:24
【问题描述】:

我正在学习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

【问题讨论】:

  • 这些不是引用,而是函数的地址。
  • 这可能是bool 的隐式转换,尝试在流中设置布尔 alpha 标志,看看它们是否更改为 true 而不是 1
  • 函数指针没有ostream::operator&lt;&lt;() 重载,但void* 有。 &amp;j 将匹配 void* 重载(这就是为什么这似乎有效),但函数指针不会 - 他们得到的最佳匹配是 bool 的匹配。
  • 它们的值都是 1 而不是十六进制...十六进制只是表示数字的另一种方式。就像十进制(以 10 为底)、二进制(以 2 为底)和十六进制(以 16 为底)一样。

标签: c++ memory pointers reference


【解决方案1】:

因为ostreamvoid*operator&lt;&lt; 的重载,并且任何data 指针都可以转换为void*,所以会打印ints 的地址,例如j .但是,函数指针不能转换为void*,所以这个特殊的重载是不合适的。

这时另一个operator&lt;&lt; 重载开始发挥作用,在这种情况下,这将是bool 的重载。函数指针可以转换为bool(true == 指针为非NULL)。指向f 的指针是非NULL,所以在这个转换中它的结果为true,打印为1。

【讨论】:

  • 我明白了。这是关于超载的。为什么函数指针不能转换为void*?我之前学过python,认为函数只是另一种形式的数据..在C中似乎不同..
【解决方案2】:

这与引用无关。该程序不使用任何引用。您正在使用地址运算符&amp;。见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

【讨论】:

    猜你喜欢
    • 2023-01-17
    • 2011-06-04
    • 2021-10-26
    • 1970-01-01
    • 1970-01-01
    • 2011-02-02
    • 1970-01-01
    • 2022-01-01
    相关资源
    最近更新 更多