How to print member function address in C++(如何在C++中打印成员函数地址)
问题描述
看起来std::cout
不能打印成员函数的地址,例如:
It looks like std::cout
can't print member function's address, for example:
#include <iostream>
using std::cout;
using std::endl;
class TestClass
{
void MyFunc(void);
public:
void PrintMyFuncAddress(void);
};
void TestClass::MyFunc(void)
{
return;
}
void TestClass::PrintMyFuncAddress(void)
{
printf("%p
", &TestClass::MyFunc);
cout << &TestClass::MyFunc << endl;
}
int main(void)
{
TestClass a;
a.PrintMyFuncAddress();
return EXIT_SUCCESS;
}
结果是这样的:
003111DB
1
如何使用 std::cout
打印 MyFunc
的地址?
How can I print MyFunc
's address using std::cout
?
推荐答案
我不认为该语言提供了任何用于执行此操作的工具.operator <<
有用于流打印出普通 void*
指针的重载,但成员函数指针不能转换为 void*
s.这都是特定于实现的,但通常成员函数指针被实现为一对值 - 一个指示成员函数是否为虚拟的标志,以及一些额外的数据.如果函数是非虚拟函数,则额外信息通常是实际成员函数的地址.如果该函数是虚函数,则该额外信息可能包含有关如何索引到虚函数表中以查找给定接收者对象的函数的数据.
I don't believe that there are any facilities provided by the language for doing this. There are overloads for operator <<
for streams to print out normal void*
pointers, but member function pointers are not convertible to void*
s. This is all implementation-specific, but typically member function pointers are implemented as a pair of values - a flag indicating whether or not the member function is virtual, and some extra data. If the function is a non-virtual function, that extra information is typically the actual member function's address. If the function is a virtual function, that extra information probably contains data about how to index into the virtual function table to find the function to call given the receiver object.
总的来说,我认为这意味着在不调用未定义行为的情况下打印成员函数的地址是不可能的.您可能必须使用一些特定于编译器的技巧才能实现此效果.
In general, I think this means that it's impossible to print out the addresses of member functions without invoking undefined behavior. You'd probably have to use some compiler-specific trick to achieve this effect.
希望这有帮助!
这篇关于如何在C++中打印成员函数地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在C++中打印成员函数地址
基础教程推荐
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 从 std::cin 读取密码 2021-01-01