命名空间namespace

主要用途:用来解决命名冲突的问题。

1.命名空间下 可以放 函数、变量、结构体、类

2.命名空间必须定义在 全局作用域 下

3.命名空间可以嵌套命名空间

4.命名空间是开放的,可以随时往原先的 命名空间 添加内容

5.匿名(无名)命名空间

   相当于写了 static int m_C;static int m_D;
   只能在当前文件夹使用

6.命名空间可以起别名

game1.h

#pragma once
#include<iostream>
using namespace std;
namespace LOL {
	void goAtk();
}

game1.cpp

#include "game1.h"
void LOL::goAtk() {
	cout << "LOL Attack." << endl;
}

game2.h

#pragma once
#include<iostream>
using namespace std;
namespace KingGlory {
	void goAtk();
}

game2.cpp

#include "game2.h"
void KingGlory::goAtk() {
	cout << "KingGlory Attack." << endl;
}

main.cpp

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include "game1.h"
#include "game2.h"
using namespace std;

int atk = 200;
void test() {
	int atk = 100;
	cout << "局部攻击力:" << atk << endl;
	//双冒号::为作用域运算符,引用全局作用域
	cout << "全局攻击力:" << ::atk << endl;
}

namespace A {
	void func();
	int m_A = 20;
	struct Person {

	};
	class Animal {};
	namespace B {
		int m_A = 10;
	}
}

void test02() {
	cout << "作用域B下的m_A为:" << A::B::m_A << endl;
}

//此A命名空间会与上定义的A合并
namespace A {
	int m_B = 1000;
}

void test03() {
	cout << "A::下的m_A为:" << A::m_A << ",m_B为:" << A::m_B << endl;
}

//相当于写了 static int m_C;static int m_D;
//只能在当前文件夹使用
namespace {
	int m_C = 0;
	int m_D = 0;
}

namespace veryLongName {
	int m_A = 0;
}
void test04() {
	//起别名
	namespace veryShortName = veryLongName;
	cout <<"veryLongName:" << veryLongName::m_A << endl;
	cout <<"veryShortName:" << veryShortName::m_A << endl;
}

int main() {
	/*
	cout << "Hello World!" << endl;
	system("pause");
	test();
	*/
	LOL::goAtk();
	KingGlory::goAtk();
	test02();
	test03();
	test04();
	return EXIT_SUCCESS;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值