C++中关于命名空间
来源:互联网 发布:小米note网络制式 编辑:程序博客网 时间:2024/05/16 11:08
在C++中有一种很方便的结构,那就是namespce.尽管namespace std;违背了命名空间起初的原则,但是不可否认它确实为我们带来了很多的方便.
当然,我们可以自定义一个namespace,如何声明和调用它呢?
通过例子来帮助我们理解这些概念.
如:
#ifndef NAME_H
#define NAME_H
#pragma once
#define NAME_H
#pragma once
#include
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++中一种很重要的思想,它能简化编程.
注:转载出自:http://blog.chinaunix.net/uid-20614040-id-1915609.html
0 0
- C++中关于命名空间
- 关于xml命名空间(整理中。。。)
- 关于flex中mx_internal命名空间
- as3中关于命名空间的使用
- 关于js中namespace命名空间模式
- 关于js中namespace命名空间模式
- C/C++:命名空间
- 关于未命名空间
- 关于Hibernate命名空间
- 关于命名空间
- 关于命名空间
- 关于 c++ 命名空间
- 关于Struts2命名空间
- 关于C++命名空间
- 关于命名空间
- C++(二)关于命名空间(转)
- C++-namespace(命名空间)
- C++-namespace(命名空间)
- 作为一个新人,怎样学习嵌入式Linux -----韦东山老师
- 网站发布
- Java彩信接口开发经验及具体开发实现
- 从1.5k到18k, 一个程序员的5年成长之路
- CSDN对韦的一段采访,看后心情Hold不住了
- C++中关于命名空间
- 【C/C++】C++中类访问权限控制
- c++ try_catch throw
- 为什么C++中千万不要返回局部对象或变量的引用和指针
- 持续集成(CI)工具------Hudson/Jenkins(Continuous Integration)安装与配置详解
- C++中inline函数
- C++_友元函数
- this kernel requires an x86-64 CPU, but only detected an i686 CPU
- java反射机制学习