1.2 命名空间

C++在大型项目中常需多团队合作,会出现起名重复问题,为此提供了命名空间来解决。文中介绍了命名空间的实现原理,还提到C++特有库使用std命名空间。同时讲解了using关键字在命名空间方面的两种用法,并强调头文件中不能用using关键字,否则会导致命名空间污染。

C++经常需要多个团队合作来完成大型项目。多个团队就常常出现起名重复的问题,C++就提供了命名空间来解决这个问题。
比如团队A和团队B都需要定义一个叫做Test的类。

这里用代码简单演示:

//mian.cpp
#include<iostream>
#include"ATest.h"
#include"BTest.h"
int main(){
    test();
    return 0;
}
//ATest.h
#pragma once
void test();
//BTest.h
#pragma once
void test();
//ATest.cpp
#include<iostream>
#include"ATest.h"
void test(){
    std::cout << "A::test()" << std::endl;
}
//BTest.cpp
#include<iostream>
#include"BTest.h"
void test(){
    std::cout << "B::test()" << std::endl;
}

解决方案:

//main.cpp
#include<iostream>
#include"ATest.h"
#include"BTest.h"
int main(){
    A::test();
    B::test();
    return 0;
}
//ATest.h
#pragma once
namespace A {
    void test();
}
//BTest.h
#pragma once
namespace B {
     void test();
}
//ATest.cpp
#include<iostream>
#include"ATest.h"
namespace A {
void test(){
    std::cout << "A::test()" << std::endl;
}       
}
//BTest.cpp
#include<iostream>
#include"BTest.h"
namespace B {
void test(){
    std::cout << "B::test()" << std::endl;
}
}

顺便提两点:
命名空间的实现原理,C++最后都要转化为C来执行程序。在namespace A中定义的Test类,其实全名是A::Test。

C++所有特有的库(指c没有的库),都使用了std的命名空间。比如最常用的iostream。

using关键字设计的目的之一就是为了简化命名空间的。using关键字在命名空间方面主要有两种用法。

  1. using
    命名空间::变量名。这样以后使用此变量时只要使用变量名就可以了。举个例子。

    //main.cpp
    #include<iostream>
    #include"ATest.h"
    #include"BTest.h"
    using A::test;
    int main(){
        test();
        return 0;
    }
    
  2. using namspce命名空间。这样,每一个变量都会在该命名空间中寻找。举个例子。

    //main.cpp
    #include<iostream>
    #include"ATest.h"
    #include"BTest.h"
    using namespace A;
    int main(){
        test();
        return 0;
    }
    

    所以,头文件中一定不能使用using关键字。会导致命名空间的污染。还是用刚才的代码演示。

    解决方案:

    //main.cpp
    #include<iostream>
    #include"ATest.h"
    #include"BTest.h"
    int main(){
        test();
        return 0;
    }
    
    //ATest.h
    #pragma once
    namespace A {
        void test();
    }
    using namespace A;
    
    //BTest.h
    #pragma once
    namespace B {
         void test();
    }
    using namespace B;
    
    //ATest.cpp
    #include<iostream>
    #include"ATest.h"
    namespace A {
    void test(){
        std::cout << "A::test()" << std::endl;
    }       
    }
    
    //BTest.cpp
    #include<iostream>
    #include"BTest.h"
    namespace B {
    void test(){
        std::cout << "B::test()" << std::endl;
    }
    }
    

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-4CxcOSvR-1667047884369)(c++%E5%9F%BA%E7%A1%80.assets/image-20220928181752016.png)]

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值