問題描述
看起來std::cout
不能打印成員函數(shù)的地址,例如:
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
?
推薦答案
我不認為該語言提供了任何用于執(zhí)行此操作的工具.operator <<
有用于流打印出普通 void*
指針的重載,但成員函數(shù)指針不能轉換為 void*
s.這都是特定于實現(xiàn)的,但通常成員函數(shù)指針被實現(xiàn)為一對值 - 一個指示成員函數(shù)是否為虛擬的標志,以及一些額外的數(shù)據(jù).如果函數(shù)是非虛擬函數(shù),則額外信息通常是實際成員函數(shù)的地址.如果該函數(shù)是虛函數(shù),則該額外信息可能包含有關如何索引到虛函數(shù)表中以查找給定接收者對象的函數(shù)的數(shù)據(jù).
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.
總的來說,我認為這意味著在不調用未定義行為的情況下打印成員函數(shù)的地址是不可能的.您可能必須使用一些特定于編譯器的技巧才能實現(xiàn)此效果.
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++中打印成員函數(shù)地址的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!