c和c++中函数指针之间的差异

difference between function pointers in c and c++

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

可能重复:
如何使用cout打印函数指针?

c和c++中的函数指针有什么区别?当我在c++中打印函数指针时,它给出的是1,但在c中,它给出了一个地址。

#include <iostream>
int fun()
{}
typedef int (*f)();

int main()
{
    f test = fun;
    std::cout << reinterpret_cast<f>(test);
}

#include <stdio.h>
int fun()
{}
int (*f)();
int main()
{
    f = fun;
    printf("%p", f);
}

函数指针无法转换为void*,因此在使用C++i/o的程序中,它会转换为bool。C程序也是一个C++程序。当您将它编译为C++时,应该不会有任何区别。

干杯&hth。,

主要区别在于您使用的打印机制。std::cout和printf有不同的语义。std::cout将指针称为布尔数据,并打印0或1而不是地址。

真正的问题是,当您流式传输指向函数的指针时,带有"/p"的printf和cout之间有什么区别。

要在C++中打印出指向函数的指针,请尝试将其强制转换为char*并遍历字节(长度为sizeof(test((。我想你会发现它类似于"%p">