C++namespace命名空间

版权声明: https://blog.csdn.net/qq_40794602/article/details/85093993

one.h文件

#pragma once
#include<iostream>
using namespace std;

namespace oneDog
{
	void oneDogName();
}

one.cpp文件

#include"one.h"

void oneDog::oneDogName()  //记住在这里实现的时候要加上命名空间
{
	cout << "我是oneDog" << endl;
}

 main.cpp文件

#include<iostream>
#include"one.h"
using namespace std;
//1.命名空间下可以放函数方法类,变量,结构体
//2.命名空间必须定义在全局作用域下
//3.命名空间可以嵌套命名空间
namespace A
{
	namespace B
	{
		void test()
		{
			cout << "A作用域下嵌套的B作用域下的test函数" << endl;
		}
	}
}
//4.命名空间是开放的,可以随时为原来的命名空间添加新的内容
namespace A
{
	void test()
	{
		cout << "A命名空间新添加的test函数" << endl;
	}
}
//5.匿名命名空间,这个里面的内容只能被当前文件使用
namespace
{
	void test1()
	{
		cout << "我是匿名命名空间中的test1函数" << endl;
	}
}
//6.可以为命名空间起一个别名
namespace verylongName
{
	void test()
	{
		cout << "我是换过名后的命名空间下的test函数" << endl;
	}
}
namespace veryshortName = verylongName;
int main()
{
	oneDog::oneDogName();  //调用noeDog命名空间下的oneDogName函数
	A::B::test();  //调用嵌套命名空间作用域的test函数
	A::test();  //调用为A命名空间新添加的test函数
	test1();
	veryshortName::test();

	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40794602/article/details/85093993
今日推荐