命名空间可以放到头文件里面,但是尽量不要这么做。我下面的例子基本把情况概括。没有注释。。。如有不妥请大神指教
1.第一种方式,不带类的命名空间
// test.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <typeinfo.h>
namespace mybuff{
int value = 0;
int sum(int x,int y){
return x+y;
}
int sum1(int x,int y);
}
int mybuff::sum1(int x,int y){
std::cout<<"hello world";
return x-y;
}
using namespace mybuff;
int _tmain(int argc, _TCHAR* argv[])
{
//std::cin>>mybuff::value;
//std::cout<<"\nyou entered"<<mybuff::value<<std::endl;
std::cout<<sum(1,1)<<std::endl;
std::cout<<sum1(2,1)<<std::endl;
system("pause");
return 0;
}
2.命名空间里面包含类,用using namespacd
#include "stdafx.h"
#include <iostream>
#include <typeinfo.h>
namespace mybuff{
class mytest{
public:
int sum(int x,int y);
};
class mytest2{
public:
int sum(int x,int y);
};
}
int mybuff:: mytest::sum(int x,int y){
return x+y;
}
int mybuff:: mytest2::sum(int x,int y){
return x+y;
}
using namespace mybuff;
int _tmain(int argc, _TCHAR* argv[])
{
//std::cin>>mybuff::value;
//std::cout<<"\nyou entered"<<mybuff::value<<std::endl;
mytest a;
mytest2 b;
std::cout<<a.sum(1,1)<<std::endl;
std::cout<<b.sum(1,3)<<std::endl;
system("pause");
return 0;
}
3.不带 using namespace std
#include "stdafx.h"
#include <iostream>
#include <typeinfo.h>
namespace mybuff{
class mytest{
public:
int sum(int x,int y);
};
class mytest2{
public:
int sum(int x,int y);
};
}
int mybuff:: mytest::sum(int x,int y){
return x+y;
}
int mybuff:: mytest2::sum(int x,int y){
return x+y;
}
int _tmain(int argc, _TCHAR* argv[])
{
//std::cin>>mybuff::value;
//std::cout<<"\nyou entered"<<mybuff::value<<std::endl;
mybuff::mytest a;
mybuff::mytest2 b;
std::cout<<a.sum(1,1)<<std::endl;
std::cout<<b.sum(1,3)<<std::endl;
system("pause");
return 0;
}