C++中关于命名空间

来源:互联网 发布:小米note网络制式 编辑:程序博客网 时间:2024/05/16 11:08
  在C++中有一种很方便的结构,那就是namespce.尽管namespace std;违背了命名空间起初的原则,但是不可否认它确实为我们带来了很多的方便.
  当然,我们可以自定义一个namespace,如何声明和调用它呢?
通过例子来帮助我们理解这些概念.
如:
#ifndef NAME_H
#define NAME_H
#pragma once
#include
using namespace std;
namespace example{
 void f(){
   cout<<"This is an example\n";
 }
 int add(int a,int b){
  return (a+b);
 }
}
#endif
将以上代码保存为name.h
 
主函数见下:
#include "name.h"
using example::f;   //调用在name.h中定义的命名空间example
using example::add; //调用在name.h中定义的命名空间example
int main(){
 int a,b;
 cout<<"Enter two numbers\n";
 cin>>a>>b;
 f();
 cout<<"The result =="<<add(a,b)<<endl;
 return 0;
}
除了上面的调用方法之外,还可以通过下面的方法:
1.直接在main函数前调用它,如:
#include "name.h"
using namespace example;
int main(){
 int a,b;
 cout<<"Enter two numbers\n";
 cin>>a>>b;
 f();
 cout<<"The result =="<<add(a,b)<<endl;
 return 0;
}
2.在main函数体中进行调用,如:
#include "name.h"
int main(){
 int a,b;
 cout<<"Enter two numbers\n";
 cin>>a>>b;
 example::f();
 cout<<"The result =="<<example::add(a,b)<<endl;
 return 0;
 
命名空间是C++中一种很重要的思想,它能简化编程.


注:转载出自:http://blog.chinaunix.net/uid-20614040-id-1915609.html

0 0
原创粉丝点击