c++ 指向函数的指针没有改变

标签 c++ function pointers

我已经定义了一些函数并且我打印它们的地址是这样的:

#include<iostream>
#include <string>

using std::cout;

std::string func()
{
    return "hello world\n";

}

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

可以吗还是应该有所不同?

最佳答案

不存在 operator<< 的重载对于 std::ostream它需要一个函数指针。因此 operator<<(std::ostream&, bool)过载是首选。函数的地址总是计算为 true转换为 bool 时.因此,打印了 1。

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

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

Live Demo

但是,正如 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;

Live Demo

关于c++ 指向函数的指针没有改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34255572/

相关文章:

c++ - C++有自初始化指针吗

c++ - Swig:如何包装 double&(double 通过引用传递)?

c++ - Qt5 QMediaPlayer 使用程序自带的编解码器

Javascript 函数仅在有警报时才有效

C++ 将静态二维 double 组转换为 double **

来自指针回溯的 C++ 段错误

c++ - 是否可以检查共享指针是否在 native 单元测试中返回 nullptr?

java - 使用Java修改exe资源?

Python - 动态调用具有动态数量参数的方法。反射?

java - 我如何开始优化我的 Java 代码? - CPU 处于 100%