局部类(仅限 C++)
在函数定义中声明 本地类 。 本地类中的声明只能使用类型名称,枚举,外层作用域中的静态变量以及外部变量和函数。
例如:
int x; // global variable
void f() // function definition
{
static int y; // static variable y can be used by
// local class
int x; // auto variable x cannot be used by
// local class
extern int g(); // extern function g can be used by
// local class
class local // local class
{
int g() { return x; } // error, local variable x
// cannot be used by g
int h() { return y; } // valid,static variable y
int k() { return ::x; } // valid, global x
int l() { return g(); } // valid, extern function g
};
}
int main()
{
local* z; // error: the class local is not visible
// ...}本地类的成员函数必须在其类定义中定义 (如果它们是完全定义的)。 因此,本地类的成员函数是内联函数。 与所有成员函数一样,在本地类的作用域中定义的那些函数不需要关键字 inline。
本地类不能具有静态数据成员。 在以下示例中,尝试定义本地类的静态成员会导致错误:
void f()
{
class local
{
int f(); // error, local class has noninline
// member function
int g() {return 0;} // valid, inline member function
static int a; // error, static is not allowed for
// local class
int b; // valid, nonstatic variable
};
}
// . . .外层函数对本地类的成员没有特殊访问权。