在C++中有一种很方便的结构,那就是namespce.尽管namespace std;违背了命名空间起初的原则,但是不可否认它确实为我们带来了很多的方便.
当然,我们可以自定义一个namespace,如何声明和调用它呢?
通过例子来帮助我们理解这些概念.
如:
#ifndef NAME_H
#define NAME_H
#pragma once
#define NAME_H
#pragma once
#include<iostream>
using namespace std;
using namespace std;
namespace example{
void f(){
cout<<"This is an example\n";
}
int add(int a,int b){
return (a+b);
}
}
#endif
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
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;
}
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;
}
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;
}
int a,b;
cout<<"Enter two numbers\n";
cin>>a>>b;
example::f();
cout<<"The result =="<<example::add(a,b)<<endl;
return 0;
}
命名空间是C++中一种很重要的思想,它能简化编程.
