指向函数的c++指针未更改

c++ pointer to function not changed

本文关键字:指针 c++ 函数      更新时间:2023-10-16

我定义了一些函数,并打印它们的地址如下:

#include<iostream>
#include <string>
using std::cout;
std::string func()
{
    return "hello worldn";
}
int func2(int n)
{
    if (n==0)
    {
        cout << func2 << std::endl;
        return 1;
    }
    cout << func2 << std::endl;
    return n + func2(n - 1);
}
//================================================
int main()
{
    int (*fun)(int) = func2;
    cout << fun;
    cout << std::endl << func2(3);
}

当我打印函数的名称(地址)时,它们都会在我的编译器(Mingw gcc 4.8)上打印1

可以还是应该有所不同?

对于采用函数指针的std::ostream,不存在operator<<的重载。因此优选operator<<(std::ostream&, bool)过载。函数的地址在转换为bool时总是求值为true。因此,打印出1。

或者,如果函数指针不大于数据指针的大小,则可以通过reinterpret_cast将函数指针强制转换为void*,并调用operator<<(std::ostream&, void*)重载,从而打印出函数的实际地址。

int (*fun)(int) = func2;
std::cout << reinterpret_cast<void*>(fun) << std::endl;

实时演示

然而,正如Neil和M.M在评论中正确提到的那样,没有从函数指针到数据指针的标准转换,这可能会引发未定义的行为。

或者,在我看来,您可以将函数指针格式化为char数组缓冲区,并以以下方式将其地址转换为字符串:

unsigned char *p = reinterpret_cast<unsigned char*>(&func2);
std::stringstream ss;
ss << std::hex << std::setfill('0');
for(int i(sizeof(func2) - 1); i >= 0; --i) ss << std::setw(2) 
                                              << static_cast<unsigned int>(p[i]);
std::cout << ss.str() << std::endl;

实时演示

您没有打印地址,因为它现在已转换为布尔值。

但你可以这样做:

std::cout << reinterpret_cast<unsigned long long int *>(func2) << std::endl;

现在您将获得实际地址。