C++命名空间(一)

32 篇文章 0 订阅

一、namespace命名空间

  1. 命名空间用途:解决名称冲突
  2. 命名空间下可以存放 : 变量、函数、结构体、类…
  3. 命名空间必须要声明在全局作用域
  4. 命名空间可以嵌套命名空
  5. 命名空间是开放的,可以随时将新成员添加到命名空间下
  6. 命名空间可以匿名的
  7. 命名空间可以起别名

    使用示例

main.c

#include <iostream>
#include"start1.h"
#include"start2.h"
#include"start3.h"

using namespace std;

namespace A {
    int A_a=10;
    int A_b=20;
}

void ns() {
    using namespace s1;
    using namespace A;
    test();
    cout << A_a << endl;
}

int main()
{
    bool tag = true;
    namespace ABC = A;

    s1::test();
    s2::test();
    s3::s4::test();

    cout << "Hello World!"<<endl;
    cout << ABC::A_a << endl;
    cout<< A::A_b << endl;
    ns();

    system("pause");
    return EXIT_SUCCESS;
}

start3.h、start3.cpp

//start3.h
#pragma once
#include<iostream>
using namespace std;

namespace s3 {
	namespace s4 {
		void test();
	}
}


//start3.cpp
#include"start3.h"

void s3::s4::test() {
	cout<<"start 3" << endl;
}

start2.h、start2.cpp


//start2.cpp
#pragma once
#include<iostream>
using namespace std;

namespace s2
{
	void test();
}


//start2.h
#include"start2.h"

void s2::test() {
	cout<<"start 2" << endl;
}

start1.h、start1.cpp


//start.h
#pragma once
#include<iostream>
using namespace std;

namespace s1
{
	void test();
}

//start1.cpp
#include"start1.h"

void s1::test() {
	cout << "start 1"<<endl;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值