现在的位置: 首页 > 综合 > 正文

了解C++11(二)—— __func__预定义标识符

2014年09月02日 ⁄ 综合 ⁄ 共 617字 ⁄ 字号 评论关闭

c++11支持__func__预定义标识符,主要用在调试中。c99也支持__func__。如:

const char * Hello()
{
    return __func__;
}

__func__会返回函数的名字。

实际上编译器会(隐式的)在函数中(function-local)定义__func__标识符:

const char * Hello()
{
    static const char __func__[] = “Hello”; // function-name
    return __func__;
}

c++11允许__func__用在类或结构体中。

struct TestStruct
{
    TestStruct() : name(__func__) {}
    const char *name;
};
 
int main()
{
    TestStruct ts;
    cout << ts.name << endl; // TestStruct
 
    return 0;
}

__func__不能用于函数的默认形参,因为这时候__func__还没有定义。

void func(const char * s = __func__); // error: __func__ is undeclared

c++11标准未规定变量__func__是否拥有一个地址(用于区分其它对象),这取决于编译器实现。

It is unspecified whether such a variable has an address distinct from that of any other object in the program.

抱歉!评论已关闭.