在详细说明符中使用 typedef 名称

发布于 2024-12-18 13:15:02 字数 249 浏览 2 评论 0原文

根据 ($ 3.4.4) 后面跟着类键的 typedef 名称是无效的。但我不确定哪个范围?例如:在下面的内容中,如果在块(例如函数内部)中使用了详细说明符,编译器不会抱怨。

typedef class { /* ... */ } S;

// invalid
class S;

// ok
void foo() {
   class S;
}

使用 typedef-name 在本地范围内声明类是否有效,为什么?

According to ($ 3.4.4) A typedef name followed by a class-key is invalid. But I'm not sure about which scope? For example: In the following, compiler doesn't complain if elaborated specifier was used in a block such as inside a function.

typedef class { /* ... */ } S;

// invalid
class S;

// ok
void foo() {
   class S;
}

Is it valid to declare a class inside a local scope with typedef-name, Why?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

套路撩心 2024-12-25 13:15:02

7.1.3 第 3 段讲述:

在给定范围内,typedef 说明符不得用于重新定义
thascope 中声明的任何类型的名称,以引用不同的类型
类型。
[示例:

class complex { /* ... */ }; 
typedef int complex; //

错误:重新定义

然后是:

—结束示例]同样,在给定范围内,类或枚举
不得使用与 typedef-name 相同的名称进行声明
在该范围内声明并引用类以外的类型或
枚举本身。 [示例:

typedef int complex;
class complex { /* ... */ };

// 错误:重新定义

这是您的示例。

7.1.3 paragraph 3 tells :

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

Then it goes :

—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

This is your example.

微凉 2024-12-25 13:15:02

问题是您声明的类没有名称,但使用了别名(typedef)。后来,您使用相同的名称来声明而不定义另一个类(我知道这不是意图,但编译器是这么理解的),并且它的名称与 typedef 发生冲突。当您在 foo() 内执行相同的操作时,这是一个单独的范围,因此是可以接受的。但请注意,foo() 中的“class S”与第一行中声明的类型不同。

The problem is that you declared the class with no name, but with an alias (the typedef). Later, you used the same name to declare without defining another class (I know that was not the intention, but that's what the compiler understood) and its name clashed with the typedef. When you did the same thing inside foo(), that was a separated scope and so was acceptable. But notice that the 'class S' inside foo() is NOT the same type as that declared in the first line.

不及他 2024-12-25 13:15:02

在函数外部,您不能在同一命名空间中声明与 typedef 同名的类。

在函数内部,您正在声明一个新类,其作用域位于函数内部。它与周围命名空间中声明的匿名类不同。在函数内,这隐藏了 typedef 的声明。

Outside the function, you cannot declare a class with the same name as a typedef in the same namespace.

Inside the function, you are declaring a new class, scoped inside the function. It is not the same as the anonymous class declared in the surrounding namespace. Within the function, this hides the declaration of the typedef.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文