c++ 静态变量初始化测验

栏目: C++ · 发布时间: 7年前

内容简介:http://stackoverflow.com/questions/32362904/static-variables-initialization-quiz
#include <stdio.h>

class C
{
   public:
          static int i;
          static int j;
};

int i = 10;
int C::i = 20;
int C::j = i + 1;

int main ()
{
    printf("%d", C::j);

    return 0;
}
What is the value of: C::j

我正在读一个c测验,遇到以下问题.我以为答案是11.

int C :: j = i 1;

因为它正在访问非静态i是10?那么,我以为11应该是答案?

我编译并运行这个代码通过视觉工作室,它打印21.这是令我困惑的.有人可以解释为什么会发生这种情况吗?我失踪了什么

[basic.lookup.qual] / 3

In a declaration in which the declarator-id is a qualified-id, names used before the qualified-id being declared

are looked up in the defining namespace scope; names following the qualified-id are looked up in the scope

of the member’s class or namespace.

int C::j = i + 1;

declarator-id,即正在声明的实体的名称是C :: j,它是一个限定id.因此,我跟随它在C的范围内查找,并且指C :: i.

在技​​术上,在定义静态数据成员时,初始化器可以被认为是在类的范围内,并且在全局变量之前会发现类成员.

这是一个相同的规则,可以确保当一个成员函数被定义为行之外时,函数名称之后的名称将在类范围内查找,并且如果它们引用类成员则不需要明确的限定.更不寻常的是,这被应用于静态数据成员的定义,但它是完全一致的.

http://stackoverflow.com/questions/32362904/static-variables-initialization-quiz


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

The Mechanics of Web Handling

The Mechanics of Web Handling

David R. Roisum

This unique book covers many aspects of web handling for manufacturing, converting, and printing. The book is applicable to any web including paper, film, foil, nonwovens, and textiles. The Mech......一起来看看 《The Mechanics of Web Handling》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

SHA 加密
SHA 加密

SHA 加密工具

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器