2015-02-10 85 views
-3

我有以下代码:类型名称路径是由一个静态变量隐藏

struct type1 
{ 
    struct type2 
    { 

    }; 
    int tyep2; // No conflic with real type name path: type1::type2 
}; 

struct type4 
{ 
    struct type5 
    { 

    }; 
    static int type5; // No conflic with real type name path: type4::type5 

}; 

int type4::type5; // this path name is equal to type name path: struct type4::type5 


int _tmain(int argc, _TCHAR* argv[]) 
{ 
    type1::type2 var1; // is ok 
    type4::type5 Var2; // is ok 
    type4::type5 = 0; // is ok, but the static variable has obscured my type 
    return 0; 
} 

我的问题是:

  1. 为什么静态变量成的Type5隐藏式 type4 :: type5
  2. 为什么编译呃当我声明type5时不会产生错误变量?
  3. 在哪里可以阅读有关C++标准规范中的这种行为?请发表最终的提取物
+0

对不起,我发布了一个错误代码 – AngeloDM 2015-02-10 21:54:54

+0

为什么你说“静态变量已经模糊了你的类型”? – 2015-02-10 22:56:38

回答

2

你的程序是形成不良的,因为名字不确定性(忽略拼写错误“tyep的“你已经散落)

§10.2会员名称查找

成员名称查找确定类范围(3.3.7)中名称(id-expression)的含义。名称 查找可能会导致模糊,在这种情况下,该程序不合格。对于id表达式,名称 的查找从此类的范围开始;对于合格id,名称查找从嵌套名称 说明符的范围开始。名称查找发生在访问控制之前(3.4,第11章)。

不要这样做:

struct type5 
{ 
    //... 
}; 
static int type5; 

毫不奇怪,这并不编译我的ideone。 Live Demo

+0

感谢您的评论和发布。 我不明白为什么我纠正我的代码后收到负面评论。 – AngeloDM 2015-02-10 22:17:02

+0

@AngeloDM:我的猜测是因为你的问题无疑是初学程序员学习的东西;不要给两个同名的东西。您特别要求在标准中提及,所以我回答了这个问题,但这个想法是我不应该需要。 – AndyG 2015-02-10 22:28:25

0

1)T YE P5!=成的Type5

2)同样的原因

+0

对不起,我发布了一个错误代码 – AngeloDM 2015-02-10 21:55:10