namespace作用是避免程序中的命名冲突,传统的C++程序是只有一个namespace,现在程序越来越复杂,为了防止程序员在合并不同程序时出现函数、类、结构体等命名的重复,所以用到命名空间。
下面主要 使用一个案例介绍其使用:
首先一个namespace在一个头文件Name.h中,代码如下:
#pragma once
#include<math.h>
#include<iostream>
struct point3D
{
float x;
float y;
float z;
};
struct point2D
{
float x;
float y;
};
namespace Name
{
class point
{
public:
float distance(point3D p, point3D q);
float distance(point2D p, point2D q);
void showInfo(point3D p);
void showInfo(point2D p);
};
class plane
{
public:
void showInfo(point3D p, point3D q, point3D r);
};
}
在Name.cpp中具体函数实现代码:
#include"Name.h"
float Name::point::distance(point3D p, point3D q)
{
float dx = p.x - q.x;
float dy = p.y - q.y;
float dz = p.z - q.z;
return sqrt(dx*dx + dy*dy + dz*dz);
}
float Name::point::distance(point2D p, point2D q)
{
float dx = p.x - q.x;
float dy = p.y - q.y;
return sqrt(dx*dx + dy*dy);
}
void Name::point::showInfo(point2D p)
{
std::cout << p.x << "\t" << p.y << std::endl;
}
void Name::point::showInfo(point3D p)
{
std::cout << p.x << "\t" << p.y << "\t" << p.z << std::endl;
}
void Name::plane::showInfo(point3D p, point3D q, point3D r)
{
std::cout << "第一个点:" << p.x << "\t" << p.y << "\t" << p.z << std::endl;
std::cout << "第二个点:" << q.x << "\t" << q.y << "\t" << q.z << std::endl;
std::cout << "第三个点:" << r.x << "\t" << r.y << "\t" << r.z << std::endl;
}
在测试文件中,给出如下两种测试代码,均可以进行测试:
#include"Name.h"
using namespace Name;
void main()
{
point3D P;
point3D Q;
point3D R;
P.x = 0; P.y = 0; P.z = 0;
Q.x = 1; Q.y = 1; Q.z = 1;
R.x = 2; R.y = 2; R.z = 2;
point example;
float dis = example.distance(P, Q);
std::cout << "两点间间距:" << dis << std::endl;
example.showInfo(P);
example.showInfo(Q);
plane example_plane;
example_plane.showInfo(P, Q, R);
system("pause");
}
以及下面的代码:
#include"Name.h"
void main()
{
point3D P;
point3D Q;
point3D R;
P.x = 0; P.y = 0; P.z = 0;
Q.x = 1; Q.y = 1; Q.z = 1;
R.x = 2; R.y = 2; R.z = 2;
using Name::point;
point example;
float dis = example.distance(P, Q);
std::cout << "两点间间距:" << dis << std::endl;
example.showInfo(P);
example.showInfo(Q);
using Name::plane;
plane plane_example;
plane_example.showInfo(P, Q, R);
system("pause");
}
最后的显示结果如下: