本文介绍了如何在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\n", &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?

推荐答案

我不相信有这样的语言提供任何设施。对于流打印出正常的 void * 指针,有 operator 的重载,但成员函数指针不能转换为 void * 。这是所有实现特定的,但是通常成员函数指针被实现为一对值 - 指示成员函数是否是虚拟的标志和一些额外的数据。如果函数是非虚函数,那么额外信息通常是实际成员函数的地址。如果函数是虚函数,那么额外的信息可能包含关于如何索引到虚函数表中的数据,以找到给定接收者对象调用的函数。

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

1403页,肝出来的..

09-06 08:45