如何在C++中打印成员函数地址

2023-02-22C/C++开发问题
26

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

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&amp;()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6