C++学习笔记之 命名空间

命名空间

#include <iostream>
#include <cstdio>

// using namespace std::cout; // 使用std中的cout
using namespace std; // 使用std中的所有定义

namespace A
{
    int a = 0;
}

namespace B
{
    int a = 10;
}

// 用途:解决名称冲突
void test1(void)
{
    cout << "test1:" << endl;
    cout << "A::a = " << A::a << "\nB::a = " << B::a << endl;
}

// 命名空间必须声明在全局作用域下
void test(void)
{
    // 局部作用域下不能定义命名空间
    //namespace _test
    //{
    //    int a = 0;
    //}
}

// 命名空间可以嵌套命名空间
namespace C
{
    int int_a = 0;
    namespace D
    {
        int int_a = 1;
    }
}

void test2(void)
{
    cout << "\ntest2:" << endl;
    printf("C::int_a = %d\nC::D::int_a = %d\n",C::int_a,C::D::int_a);
}

// 命名空间是开放的,可以随时添加新成员
// 同名的命名空间做 合并操作
namespace C
{
    char char_a = 'C';
    void hello();
}

void C::hello()
{
    printf("Hello\n");
}

void test3(void)
{
    cout << "\ntest3:" << endl;
    cout << "C::char_a = " << C::char_a << endl;
    C::hello();
}

// 命名空间可以匿名
namespace
{
    int quanju = 0; // 命名空间是匿名时 变量前隐式添加了关键字static,相当于全局变量
}

void test4(void)
{
    cout << "\ntest4:" << endl;
    cout << quanju << endl;
}

// 命名空间可以起别名
namespace long_long_name
{
    int a = 0;
}

void test5(void)
{
    namespace short_name = long_long_name;
    cout << "\ntest5:" << endl;
    cout << short_name::a << endl;
}

int main(int argc, char *argv[])
{
    test1();
    test2();
    test3();
    test4();
    test5();

    return 0;
}

using指令

#include <iostream>
#include <cstdlib>

using namespace std;

// 1. using声明

namespace C
{
    char name[] = "C语言";
}

namespace cpp
{
    char name[] = "C++";
}

void test1()
{
    char name[] = "C++";

    // using C::name; // 提前告诉编译器,name用C里的
    // using声明原则与就近原则同时出现,无法使用,二义性出现
    // 无法解决,尽量避免
    cout << name << endl;
}

// 2. using编译指令

void test2()
{
    int name = 1;

    using namespace C; // 打开C命名空间
    using namespace cpp;

    cout << name << endl; // 和就近原则同时出现,优先使用就近原则
}

int main(int argc,char *argv[])
{
    test1();
    test2();

    return EXIT_SUCCESS;
}
C++
1
posted @ 2020-10-30 21:09  小宇宙zjy  阅读(66)  评论(0编辑  收藏  举报