【1】__func__預定義標識符
很多現代的編譯器都支持C99標准中的__func__預定義標識符功能,其基本功能就是返回所在函數的名字。
常見的用法,看下面這個例子:
#include <iostream> using namespace std; const char* hello() { return __func__; } const char* world() { return __func__; } int main() { cout << hello() << ", " << world() << endl; // hello, world }
上例中,定義了兩個函數hello和world。利用__func__預定義標識符,我們返回了函數的名字,並將其打印出來。
事實上,按照標准定義,編譯器會隱式地在函數的定義之后定義__func__標識符。
比如上述例子中的hello函數,其實際的定義等同於如下代碼:
const char* hello() { static const char* __func__ = "hello"; return __func__; }
【2】C++11中的區別
在C++11中,標准甚至允許其使用在類或者結構體中。可以看看下面這個例子:
#include <iostream> using namespace std; struct TestStruct { TestStruct() : name(__func__) {} const char* func() { return __func__; } // void funcFail(string func_name = __func__); // E1036 保留的標識符 "__func__" 只能在函數內部使用 const char* name; }; int main() { TestStruct ts; cout << ts.name << endl; // TestStruct cout << ts.func() << endl; // func }
從代碼中可以看到,在結構體的構造函數中,初始化成員列表使用__func__預定義標識符是可行的,其效果跟在函數中使用一樣。
不過將__fun__標識符作為函數參數的默認值是不允許的,如上例函數funcFail所示(無法編譯通過)
這是由於在參數聲明時,__func__還未被定義。
Good Good Study, Day Day Up.
順序 選擇 循環 總結