21xrx.com
2025-03-22 01:12:18 Saturday
文章检索 我的文章 写文章
C++如何输出函数名
2023-07-05 06:01:56 深夜i     15     0
C++ 输出 函数名

在C++编程中,有时我们需要输出正在执行的函数名称。这样可以方便我们调试程序,查看程序在哪些地方出现问题。本文将介绍如何在C++中输出函数名称。

使用预编译指令__FUNCTION__

C++提供了__FUNCTION__预编译指令,可以输出当前正在执行的函数名称。以下是示例代码:

#include <iostream>
using namespace std;
void test()
  cout << "function name: " << __FUNCTION__ << endl;
int main(){
  test();
  return 0;
}

输出结果为:

function name: test

使用typeid

在C++11及以上版本中,我们可以使用typeid操作符获取函数的类型信息。以下是示例代码:

#include <iostream>
#include <typeinfo>
using namespace std;
void test(){
  cout << "function name: " << typeid(__func__).name() << endl;
  //__func__也可用,与__FUNCTION__相同
}
int main(){
  test();
  return 0;
}

输出结果为:

function name: void test()

使用Boost库

Boost库是一个C++库的集合,其中包含了大量的跨平台、高效、高质量的库。这里我们使用其中的current_function获取当前函数名称。以下是示例代码:

#include <iostream>
#include <boost/current_function.hpp>
using namespace std;
void test()
  cout << "function name: " << BOOST_CURRENT_FUNCTION << endl;
int main(){
  test();
  return 0;
}

输出结果为:

function name: test

总结

本文介绍了三种获取函数名称的方法,分别是使用__FUNCTION__预编译指令、typeid操作符和Boost库的current_function。您可以根据需要选择其中的一种方法输出函数名称。希望对C++编程有所帮助。

  
  

评论区