曲径通幽论坛

 找回密码
 立即注册
搜索
查看: 2684|回复: 0
打印 上一主题 下一主题

using -- 使名字空间可见

[复制链接]

4917

主题

5879

帖子

3万

积分

GROAD

曲径通幽,安觅芳踪。

Rank: 6Rank: 6

积分
34382
跳转到指定楼层
楼主
发表于 2011-12-7 11:40:17 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
using 关键字的作用是使一个名字空间变得可见。比如容易想到,如果在程序中需要大量的使用某个名字空间中的成员,而每次又不得不使用作用域解析运算符,这样将显得冗长且繁琐。using 正是为了解决这个问题而来的。using 语句有两种通用形式:
using namespace name;
using name::member;
在第一种形式中,name 是需要使用的名字空间。所有定义在该名字空间中的成员将变得可见,并且在使用这些成员时不需要加上作用域解析运算符。比如我们常用的 using namespace std; 。
在第二种形式中,我们指定了名字空间 name 中一个特定的成员是可见的。

示例程序
[C++] 纯文本查看 复制代码
// namespace.cpp : 定义控制台应用程序的入口点。
//


#include "stdafx.h"
#include <iostream>
using namespace std;


//声明自己的名字空间
namespace CounterNameSpace {
    int upperbound;
    int lowerbound;


    class counter {
        int count;
    public:
        counter(int n)
        {
            if (n <= upperbound) 
                count = n;
            else
                count = upperbound;
        }


        void reset(int n)
        {
            if (n <= upperbound)
                count = n;
        }


        int run()     
        {
            if (count > lowerbound)
                return count--;
            else
                return lowerbound;
        }
    };
}




int _tmain(int argc, _TCHAR* argv[])
{
    //仅使用 CounterNameSpace 中的变量 upperbound
    using CounterNameSpace::upperbound;


    //现在不需要指定 upperbound 的所属作用域了
    upperbound = 100;
    
    //对于 CounterNameSpace 中的其它成员,仍然需要使用限定符
    CounterNameSpace::lowerbound = 0;


    CounterNameSpace::counter ob1(10);
    int i;


    do {
        i = ob1.run();    
        cout << i << " ";
    }while ( i > CounterNameSpace::lowerbound);
    cout << endl;


    //现在可以使用整个 CounterNameSpace 中的成员了
    using namespace CounterNameSpace;


    counter ob2(20);
    do {
        i = ob2.run();
        cout << i << " ";
    } while ( i > CounterNameSpace::lowerbound);
    cout << endl;


    ob2.reset(100);
    CounterNameSpace::lowerbound = 90;
    do {
        i = ob2.run();
        cout << i << " ";
    }while (i > CounterNameSpace::lowerbound);


    return 0;
}
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|曲径通幽 ( 琼ICP备11001422号-1|公安备案:46900502000207 )

GMT+8, 2024-5-18 00:21 , Processed in 0.077140 second(s), 24 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表