#include <iostream>
namespace func
{
void swap(int &x, int &y);
void compare(int x, int y);
/*
同一个命名空间可以在程序中出现多次,也就是说我们可以多次重复创建同一个命名空间。
这样的重复不局限在一个文件,也就是说你可以在另一个文件中对它进行重复创建,这样我们就可以
随时随地扩充这个命名空间的内容。
*/
/*
注意:我们应该尽量在命名空间之外定义函数,而在命名空间中只是生命函数。
1、这样可以保持命名空间的整洁性
2、有利于将命名空间专门存放在头文件中,而将函数的实现存放在实现文件中。
3、命名空间中的成员都是公有的,绝对不能将它们私有化。
4、命名空间可以嵌套,也就是说一个命名空间可以嵌套在另一个命名空间中
*/
}
void func::swap(int &x, int &y)
{
int temp;
std::cout << "交换前x的值:" << x << " y的值:" << y << std::endl;
temp = x;
x = y;
y = temp;
std::cout << "交换后x的值:" << x << " y的值:" << y << std::endl;
}
void func::compare(int x, int y)
{
if (x < y)
{
std::cout << "x比y小!" << std::endl;
}
else if (x == y)
{
std::cout << "x等于y!" << std::endl;
}
else
{
std::cout << "x比y大!" << std::endl;
}
}
int main()
{
int x = 5, y = 6;
func::swap(x,y);
func::compare(5,6);
return 0;
}
#include <iostream>
namespace func
{
class num // 在命名空间中可以放任何东西,包括类、对象、函数、变量、结构体等等
{
public:
num();
~num();
void swap(int &x, int &y);
void compare(int x, int y);
private:
int x;
int y;
};
}
//func::num::num()
//{
// x = 0;
// y = 0;
//}
func::num::num():x(0),y(0){}
func::num::~num()
{
std::cout << "析构函数执行..." << std::endl;
}
void func::num::swap(int &x, int &y)
{
int temp;
std::cout << "交换前x的值:" << x << " y的值:" << y << std::endl;
temp = x;
x = y;
y = temp;
std::cout << "交换后x的值:" << x << " y的值:" << y << std::endl;
}
void func::num::compare(int x, int y)
{
if (x < y)
{
std::cout << "x比y小!" << std::endl;
}
else if (x == y)
{
std::cout << "x等于y!" << std::endl;
}
else
{
std::cout << "x比y大!" << std::endl;
}
}
int main()
{
using namespace func;
int x = 5, y = 6;
num m_num;
m_num.swap(x, y);
m_num.compare(x, y);
return 0;
}
#include <iostream>
namespace people_company_boss
{
int x = 10;
}
namespace pcb = people_company_boss; // 假如命名空间很长,可以给它取个别名,注意,别名不能重名
int main()
{
std::cout << pcb::x << std::endl;
std::cout << people_company_boss::x << std::endl;
return 0;
}