Chinaunix首页 | 论坛 | 博客
  • 博客访问: 329390
  • 博文数量: 79
  • 博客积分: 2466
  • 博客等级: 大尉
  • 技术积分: 880
  • 用 户 组: 普通用户
  • 注册时间: 2006-02-07 16:47
文章分类

全部博文(79)

文章存档

2014年(3)

2012年(7)

2011年(14)

2010年(2)

2009年(2)

2008年(2)

2007年(18)

2006年(31)

分类: C/C++

2011-07-25 20:53:43

知识要点:
什么是using directive
什么是using declaration
这两者“导入”一个名字时有何区别

// using directive
int
fun1(int i) {
    using namespace std;
    int vector = 7;  // a poorly named variable, but it is legal.
    // vector a;   // error. std::vector is hidden
    return vector * i;
}

// using declaration
int
fun2(int i) {
    using std::vector;
    // int vector = 12;   // error. redeclaration of 'vector'.
    vector a; // ok.
    return i * i;
}

int
main(int argc, char *argv[]) {
    std::cout<
    return 0;
}

对fun1中的代码,<>的解释是:

One interesting aspect of using directives is that they make the names of a namespace available, but as if they were declared at *global* scope, not necessarily at the scope in which the using directive occurs. Local names will hide namespace names.

所以fun1中名字vector只有一个可见的声明,就是那个int类型的变量。std名字空间中的模板类声明被隐藏了。所以试图用vector声明一个向量会出错。

在fun2中,using declaration的作用等于是在同样的位置,同样的作用域内声明了这个名字,因此试图在同一作用域内声明一个名叫vector的int类型变量的时候,会出现“重复声明”错误。

阅读(1294) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~