在类中重排序成员声明的规则 [英] Rule of reordering member declaration in class
问题描述
我正在阅读c ++ 14 N3797,我遇到过3.3.7 / 1:
I'm reading the c++14 N3797 and I've encountered with 3.3.7/1:
如果重新排序成员在类中的声明在(1)和(2)下产生一个替换的有效
程序,该程序是错误的,没有诊断是
需要的。
If reordering member declarations in a class yields an alternate valid program under (1) and (2), the program is ill-formed, no diagnostic is required.
有(1)和(2):
在类中声明的名字不仅包括声明点后声明区域的
,
,还包括所有函数体,默认参数,
exception-specifications和brace-or-等于初始化
该类中的非静态数据成员(包括嵌套
类中的这样的东西)。
1) The potential scope of a name declared in a class consists not only of the declarative region following the name’s point of declaration, but also of all function bodies, default arguments, exception-specifications, and brace-or-equal-initializers of non-static data members in that class (including such things in nested classes).
2)在S类中,在
的上下文中引用相同的声明,并且在S的完成范围内重新求值。对于违反此规则,需要执行
诊断。
2) A name N used in a class S shall refer to the same declaration in its context and when re-evaluated in the completed scope of S. No diagnostic is required for a violation of this rule.
这是如果我们写下面的代码:
That is if we write the following:
class A
{
int a;
int b;
}
那么程序不正确。 Reorering成员声明产生一个备用有效程序:
then the program is ill-formed. Reorering member declaration yields an alternate valid program:
class A
{
int b;
int a;
}
我可能无法正确理解此规则吗?
Might I don't understand this rule correctly?
推荐答案
备用有效程序是指一种情况,其中类中的元素的每个排序产生程序的有效解释,
The "alternate valid program" is referring to a situation in which each ordering of the elements in the class yields a valid interpretation of the program, but the meaning changes depending on the ordering.
在您的情况下,更改 a的顺序
和 b
,因为它们的相对顺序不会影响程序的含义,因此定义了行为。
In your case, changing the order of a
and b
is allowed, but since their relative order can't affect the meaning of the program, the behavior is defined.
为了发生这种情况,你必须在类中使用一个已经被定义过的类以外的其他含义的名称。比如:
For this to happen, you must use a name in the class that has already been defined with some other meaning outside the class. For example:
typedef void *T;
struct whatever {
T a;
typedef long T;
};
这里, a的声明的相对顺序
,并且 T
的typedef会影响代码的含义。正如现在写的, a 有
void *
,因为全局 typedef void * c>
Here, the relative order of the declaration of a
and the typedef of T
affects the meaning of the code. As it's written right now, a
has type void *
, because the global typedef void *T;
is in scope when the T a;
is parsed.
如果,然而,我们重新排列了两个如下:
If, however, we rearranged the two so as:
typedef void *T;
struct whatever {
typedef long T;
T a;
};
... T a;
相当于 long a;
。程序的意义是不同的,因为两个声明的相对排序,所以行为是未定义的。
...the T a;
is equivalent to long a;
. The meaning of the program is different due to the relative ordering of the two declarations, so the behavior is undefined.
这篇关于在类中重排序成员声明的规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!