我已经定义了一些函数并且我打印它们的地址是这样的:
#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;
但是,正如 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;
关于c++ 指向函数的指针没有改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34255572/