标签:
#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; }
结果分别输出了最大值和最小值。
标签:
原文地址:http://my.oschina.net/donngchao/blog/527293