问题描述
看起来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++中打印成员函数地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!