[expr.ref]/1 http://eel.is/c++draft/expr.ref#1:
A postfix expression followed by a dot .
or an arrow ->
, optionally followed by the keyword template
(17.2),
and then followed by an id-expression, is a postfix expression. The postfix expression before the dot or arrow
is evaluated;67 the result of that evaluation, together with the id-expression, determines the result of the
entire postfix expression.
67) If the class member access expression is evaluated, the subexpression evaluation happens even if the result is unnecessary to
determine the value of the entire postfix expression, for example if the id-expression denotes a static member.
如果一个成员被定义为static
,那么该类只有该成员的一份副本,而不是该类的每个实例都有一份副本。静态成员可以通过类的实例(对象)来引用。脚注阐明,即使您不需要知道正在访问哪个实例对象来了解静态成员的值,也会对标识实例的表达式进行求值(并且会发生任何副作用)。
一个例子:
#include <iostream>
class foo {
public:
static int s;
};
int foo::s = 42;
int index() {
std::cout << "index returns 5\n";
return 5;
}
int main() {
foo arr[10];
std::cout << arr[index()].s << "\n";
}
只有一个s
对象,其值为42
,但是表达式arr[index()]
仍然被评估,即使不需要它的结果来确定值s
.
输出是:
index returns 5
42
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)