using声明与using编译指令

原文链接
内容全部参考自:c++ Primer Plus 第九章

命名空间:

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

需要注意的事项:
名称空间可以是全局的,也可以位于另一个名称空间中,但不能位于代码块中(我的理解是函数中)

示例代码如下:

#include <iostream>
 
using namespace std;
void funtion(void)
{
   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;
}

编译出错:

gec@ubuntu:~/demo$ g++ main.c -o main
main.c: In function ‘void funtion():
main.c:6:4: error: ‘namespace’ definition is not allowed here
    namespace Jill{
    ^~~~~~~~~
main.c: In function ‘int main():
main.c:19:2: error: ‘Jill’ has not been declared
  Jill::fetch = 3;
  ^~~~
main.c:21:10: error: ‘Jill’ has not been declared
  cout << Jill::bucket(2) << endl;

using 声明

using声明将特定的名称添加到它所属的声明区域中。

#include <iostream>
 
using namespace std;
namespace Jill{
  double bucket(double n){
  }

  double fetch;
  struct Hill{};

}

char fetch;

int main()
{
    //using Jill::fetch;

    double fetch;
    cin>>fetch;
    cin>>::fetch;
}

由于using 声明将名称添加到局部声明区域中,因此这个示例避免了将另一个局部变量也声明为fetch。另外,和其他局部变量一样,fetch也将覆盖同名的全局变量。

using 编译指令

using声明使一个名称可用,而using编译指令使所有的名称都可用。using编译指令由名称空间名和它前面的关键字using 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(){
 
	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;

}

例如有这样的代码:

static int count ;

int other();

int main()
 {
 ...
}

int other()
{
   ...
}

采用名称空间的方法如下:

namespace
{
  int count;
}

int other();

int main()
 {
 ...
}

int other()
{
   ...
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值