指向函数的c++指针未更改
c++ pointer to function not changed
我定义了一些函数,并打印它们的地址如下:
#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;
现在您将获得实际地址。
相关文章:
- 1d 智能指针不适用于语法 (*)++
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 为什么使用 "this" 指针调用派生成员函数?
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用指针从C++中的数组中获取最大值
- 助记符和指向成员语法的指针
- 嵌入方指针压缩已禁用
- 数组的指针从不分段故障
- C++ 指针的内存地址和指向数组的内存地址如何相同?
- 何时在引用或唯一指针上使用移动语义
- QMetaObject invokeMethod的基于函数指针的语法
- 如何从 std::atomic 中提取指针 T<T>?
- 如何在 C# 中映射双 C 结构指针?
- C++将浮点指针值舍入为小数位数
- 为什么++(*p)更改指针值
- 调整大小后指向元素值的指针unordered_map有效?
- 正在将指针转换为范围
- 使用指向成员的指针将成员函数作为参数传递
- 将OpenCV C++重写为EmguCV C#-如何使用指针
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错