您的位置:首页 > 编程语言 > C语言/C++

C++_命名空间namespace 与 using编译指令 与 using声明使用。

2015-08-10 18:08 761 查看
命名空间:

C++中允许用户创建自己的用户空间。可以通过关键字namespace 声明即可

需要注意的事项:

名称空间可以是全局的,也可以位于另一个名称空间中,但不能位于代码块中。

示例代码如下:

#include <iostream>

using namespace std;

namespace Jill{
	double bucket(double a){ return a + 3; }
	double fetch;
	struct Hill{
		int a;
		int b;
	};
};

int main(){

	Jill::fetch = 3;

	cout << Jill::bucket(2) << endl;

	return 0;
}




using指令:

using 声明使特定的标示符可用。

示例如下:如同使用了包里的一个变量,在接下来的作用域里不需要显示使用作用域标示符,也不能定义同名变量。

#include <iostream>

using namespace std;

namespace Jill{
	double bucket(double a){ return a + 3; }
	double fetch;
	struct Hill{
		int a;
		int b;
	};
};

int main(){

	using Jill::fetch;

	Jill::fetch = 7;
	
	double fetch;

	cin >> fetch;
	cout << fetch << endl;
	cout << Jill::fetch << endl;

	cout << Jill::bucket(2) << endl;

	return 0;
}




using 编译指令使整个名称空间可用。

#include <iostream>

using namespace std;

namespace Jill{
	double bucket(double a){ return a + 3; }
	double fetch;
	struct Hill{
		int a;
		int b;
	};
};

int main(){

	using namespace Jill;

	Jill::fetch = 7;
	
	//double fetch;

	cin >> fetch;
	cout << fetch << endl;
	cout << Jill::fetch << endl;

	cout << Jill::bucket(2) << endl;

	return 0;
}



命名空间是开放的(open),可以把名称加入到已有的名称空间中。例如下面的语句:

namespace Jill{

char * goose(const char *);

}

可以在文件的后面(或另外一个文件中)再次使用Jack名称空间来提供该函数的代码。

namespace Jill{

char * goose(const char * xx){

.........

}

}

可以给命名空间取别名。

如:namespace mvft = my_very_favorite_things;

namespace MEF = myth::elements::fire;

#include <iostream>

using namespace std;

namespace Jill{
	double bucket(double a){ return a + 3; }
	double fetch;
	struct Hill{
		int a;
		int b;
	};
	namespace Pick{
		int abile;
	}
};

namespace tank = Jill::Pick;

int main(){

	Jill::fetch = 3;
	tank::abile = 4;

	cout << tank::abile << endl;
	cout << Jill::bucket(2) << endl;

	return 0;
}



可以定义省略名称空间的名称来创建未命名的名称空间:

namespace{

int ice;

int bandycoot;

}


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: