C++ 名称空间

目录

  • 名称空间
    • using声明
    • using编译指令
    • 名称空间可以嵌套
    • 未命名的名称空间
    • 使用demo

名称空间

使用关键字namespace创建一个名称空间

namespace Jill
{
	double fetch;
	int data;
}

通过作用域解析运算符::来访问给定名称空间中的名称

Jill::data = 10;

using声明

using声明由被限定的名称和它前面的关键字using组成

using Jill::fetch

using编译指令

using编译指令由名称空间名和它前面的关键字using namespace组成,它使名称空间中的所有名称都可用,而不需要使用作用域解析运算符。

using namespace Jill;

名称空间可以嵌套

namespace element
{
	namespace file
	{
		int flame;
	}
	float water;
}

这里的flame是指element::file::flame
可以使用下面的using编译指令使内部的名称可用

using namespace element::file;

也可以在名称空间中使用using编译指令和using声明

namespace myth
{
	using Jill::fetch;
	using namespace element;
}

由于Jill::fetch现在位于名称空间myth,在这里,它被叫做fetch,因此可以这样访问它

myth::fetch;

未命名的名称空间

namespace
{
	int ice;
	int water;
}

该名称空间中声明的名称的潜在作用域为:从声明点到声明区域末尾。具体地说,不能再未命名名称空间所属文件之外的其他文件中,使用名称空间中的名称。这提供了链接性为内部的静态变量的替代品。

static int counts;
int main()
{

}

等同下方:

namespace 
{
	int counts;
}
int main()
{

}

使用demo

#ifndef DEMO_H_
#define DEMO_H_
#include
namespace test
{
    struct person
    {
        std::string name;
        int age;
    };
    //可以使用struct person 或者person
    person setperson(person &);
    void showperson(const person &);
}
#endif
#include"demo2.h"

namespace test
{
    using std::cout;
    using std::cin;
    //可以使用struct person 或者person
    person setperson(person & per)
    {
        cout << "please input the information of person:" << std::endl;
        cout << "intput name \n";
        cin >> per.name;
        cout << "intput age \n";
        cin >> per.age;
        return per;
    }
    void showperson(const person & per)
    {
        using std::cout;
        cout << "per.name = " << per.name << " ";
        cout << "per.age = " << per.age<<std::endl;
    }

}

#include"demo2.h"

int main()
{
    using namespace test;
    person p1;
    person p2;
    p2 = setperson(p1);
    showperson(p2);
    return 0;
}

运行结果:
在这里插入图片描述

你可能感兴趣的:(C++,c++,开发语言)