C++教程part1_namespace

#include <iostream>
#include "game1.h"
#include "game2.h"

// 1.resolve name conflicts
void test01()
{
    LOL::goAttack();//game1.h
    KingGlory::goAttack();//game2.h
}

//2. you can put variables, functions, structures, classes in namespace.
namespace A{
    int m_A;
    void func();
    struct Person{};
    class Animal{};
}

void test02()
{
    // 3.namespace must be declared under the global scope.
    // namespace definition is not allowed in local fields.
#if 0
    namespace B{
        int m_B;
    }
#endif
}

//4. namespace can be nested within namespace
namespace B{
    int m_A = 10;
    namespace C{
        int m_A = 20;
    }
}

void test03()
{
    std::cout << "B_m_A = " << B::m_A << std::endl;
    std::cout << "C_m_A = " << B::C::m_A << std::endl;
}

// 5.namespace is open,and content can be added at any time.
namespace B
{
    int m_B = 100;
} // namespace B

void test04()
{
    std::cout << "B_m_A = " << B::m_A << std::endl;
    std::cout << "B_m_B = " << B::m_B << std::endl;
}

// 6.namespace can be anonymous
namespace{
    // Equivalent to static 
    int m_C = 333;//static m_C
    int m_D = 444;//static m_D
}

void test05()
{
    std::cout << "m_C = " <<m_C <<std::endl;
    std::cout << "m_D = " << ::m_D << std::endl;
}

//7. namespaces can have aliases.
namespace LongName{
    int m_E = 10000;
}

void test06()
{
    namespace ShortName = LongName;
    std::cout << "namespace aliases:" << std::endl;
    std::cout << "ShortName::m_E::" <<ShortName::m_E << std::endl;
}

int main()
{

    test01();
    test03();
    test04();
    test05();
    test06();

    return EXIT_SUCCESS;
}

见代码
namespace的7种用法/功能

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值