[英]Rule of reordering member declaration in class
I'm reading the c++14 N3797 and I've encountered with 3.3.7/1: 我正在阅读c ++ 14 N3797,我遇到了3.3.7 / 1:
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)下产生备用有效程序,则程序格式错误,不需要诊断。
There are (1) and (2): 有(1)和(2):
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).
1)在类中声明的名称的潜在范围不仅包括名称的声明点后面的声明性区域,还包括所有函数体,默认参数,异常规范和非支撑或等于初始值的声明区域。该类中的静态数据成员(包括嵌套类中的这些内容)。
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.
2)在S类中使用的名称N应在其上下文中引用相同的声明,并在完成的S范围内重新评估。违反此规则不需要诊断。
That is if we write the following: 那就是我们写下面的内容:
class A
{
int a;
int b;
}
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. “备用有效程序”指的是这样一种情况,其中类中元素的每个排序产生对程序的有效解释,但含义根据顺序而改变 。
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. 在您的情况下,允许更改
a
和b
的顺序, 但由于它们的相对顺序不会影响程序的含义,因此定义了行为。
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;
};
Here, the relative order of the declaration of a
and the typedef of T
affects the meaning of the code. 这里,
a
的声明和T
的typedef的相对顺序会影响代码的含义。 As it's written right now, a
has type void *
, because the global typedef void *T;
正如它现在所写,
a
类型为void *
,因为全局typedef void *T;
is in scope when the T a;
在
T a;
范围内T a;
is parsed. 被解析。
If, however, we rearranged the two so as: 但是,如果我们重新排列这两个,那么:
typedef void *T;
struct whatever {
typedef long T;
T a;
};
...the T a;
......
T a;
is equivalent to long a;
等于
long a;
. 。 The meaning of the program is different due to the relative ordering of the two declarations, so the behavior is undefined.
由于两个声明的相对顺序,程序的含义是不同的,因此行为是未定义的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.