首页 > 其他 > 详细

初试namespace

时间:2015-11-07 14:51:20      阅读:162      评论:0      收藏:0      [点我收藏+]
#include <stdlib.h>
#include <iostream>

namespace A
{
	int x = 1;
	void fun()
	{
		std::cout << "A" << std::endl;
	}

}
namespace B
{
	int x = 2;
	void fun()
	{
		std::cout << "B" << std:: endl;
	}
	void fun2()
	{
		std::cout << "2B" << std::endl;
	}
}
using namespace B;
int main(void)
{
	std::cout << A::x << std::endl;
	B::fun();
	fun2();

	system("pause");
	return 0;


}

技术分享

以上给出了简单的namespace应用实例。

Namespaces (C++) A namespace is a declarative region that provides a scope to the identifiers (the names of types, functions, variables, etc) inside it. Namespaces are used to organize code into logical groups and to prevent name collisions that can occur especially when your code base includes multiple libraries.

以下程序的功能是根据用户需要求出数组元素的最大或者最小值。当isMax=1时求最大值,反之,求最小值。

#include <stdlib.h>
#include <iostream>
using namespace std;
namespace CompA
{
	int getMaxOrMin(int *arr, int count, bool isMax)
	{
		int temp = arr[0];
		for (int i = 1; i < count; i++)
		{
			if (isMax)
			{
				if (temp < arr[i])
				{
					temp = arr[i];
				}
			}
			else
			{
				if (temp > arr[i])
				{
					temp = arr[i];
				}
			}

		}
		return temp;

	}
}


int main(void)
{

	int arr1[4] = { 3,5,1,7 };
	bool isMax=false;
	cin >> isMax;
	cout<<CompA::getMaxOrMin(arr1, 4, isMax)<<endl;
	system("pause");
	return 0;
}

技术分享

技术分享

结果分别输出了最大值和最小值。

初试namespace

原文:http://my.oschina.net/donngchao/blog/527293

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!