根据($ 3.4.4)后跟class-key的typedef名称无效。但我不确定哪个范围?例如:在下面,如果在一个块中使用详细说明符(如函数内部),编译器不会抱怨。在详细说明符中使用typedef名称
typedef class { /* ... */ } S;
// invalid
class S;
// ok
void foo() {
class S;
}
在typedef-name的本地作用域内声明一个类是否有效,为什么?
根据($ 3.4.4)后跟class-key的typedef名称无效。但我不确定哪个范围?例如:在下面,如果在一个块中使用详细说明符(如函数内部),编译器不会抱怨。在详细说明符中使用typedef名称
typedef class { /* ... */ } S;
// invalid
class S;
// ok
void foo() {
class S;
}
在typedef-name的本地作用域内声明一个类是否有效,为什么?
7.1.3条第3款讲述:
In a given scope, a typedef specifier shall not be used to redefine the name of any type declared in thascope to refer to a different type. [Example:
class complex { /* ... */ };
typedef int complex; //
error: redefinition
便去:
—end example] Similarly, in a given scope, a class or enumeration shall not be declared with the same name as a typedef-name that is declared in that scope and refers to a type other than the class or enumera- tion itself. [Example:
typedef int complex;
class complex { /* ... */ };
// error: redefinition
这就是你们的榜样。
问题是你声明了这个类没有名字,但有一个别名(typedef)。后来,你使用相同的名称来声明而不定义另一个类(我知道这不是意图,但这正是编译器所理解的),并且它的名字与typedef冲突。当你在foo()中做同样的事情时,这是一个分离的范围,因此是可以接受的。但请注意,foo()中的'S类'与第一行中声明的类型不同。
在函数的外部,您不能在相同的命名空间中声明与typedef
具有相同名称的类。
在函数内部,您声明了一个新的类,该函数的作用域内。它与周围命名空间中声明的匿名类不同。在该功能中,这隐藏了typedef
的声明。