C++定义命名空间 , 作用域

版权声明:如需转载,请联系原作者授权... https://blog.csdn.net/Superman___007/article/details/82345638

C++作用域:1、文件 2、函数内  3类,结构体等复合语句
 命名空间:对作用域命名

命名空间分类:
    系统命名空间: std
    自定义义的命名空间:

首先我们写一个 test.cpp .

#include<iostream>
using namespace std;

int a =200;

void fun()
{
	cout<<"test::fun()"<<endl;
}

在同一路径下 , 再写一个 main.cpp 运行时会报错 , 报错 : 重复定义了 a , 因为有一个extern int a ; 声明变量来自于外部 .

#include<iostream>
using namespace std;

//声明变量来自于外部
extern int a;
int a=100;
int main()
{
	int a=300;
	cout<<a<<endl;
	return 0;
}

我们再在同一路径下 , 写一个 namespace.cpp  , 直接运行会报错说 cout 和 endl 的作用域未声明  . 

#include<iostream>
int main()
{
	cout<<"hello everyone"<<endl;
}

1使用命名空间:
    1、通过作用域符  空间名::空间成员
    2、声明命名空间:  using namespace 命名空间 ;

当我们加上 std::cout<<"hello everyone"<<std::endl ; 时就不报错了 , 因为声明了 std 的作用域 .

#include<iostream>

int main()
{
	std::cout<<"hello everyone"<<std::endl;
}

当我们将加上 using namespace std ;  它就会优先去 std 中查找 .

#include<iostream>
using namespace std;
int main()
{
	cout<<"hello everyone"<<endl;
}

2定义空间:
    namespace 命名空间
    {
        1函数
        2结构体
        3定义类
        4、定义变量,对象
        5、嵌套的命名空间    
    }

下面定义了两个命名空间 chh  和  lf  , 首先会打印 300 因为会选择局部变量优先 , 打印 a=300 ; 如果把 int a=300 ;注释掉的话 , 会报错 : 说'a'在此作用域中未声明 .

#include<iostream>
using namespace std;

namespace chh
{
	int a=100;
}

namespace lf
{
	int a=200;
}

int main()
{
	//int a=300;
	cout<<a<<endl;
}

当我们给a 添加作用域后 , 就不报错了 , 就会打印出 chh 空间里面的 a  , 打印出 100 .

#include<iostream>
using namespace std;

namespace chh
{
	int a=100;
}

namespace lf
{
	int a=200;
}

int main()
{
	//int a=300;
	cout<<chh::a<<endl;
}

所以我们可以直接在下面声明使用 chh 或者 lf 的命名空间了 , 就不用给 a 添加作用域了 .

#include<iostream>
using namespace std;

namespace chh
{
	int a=100;
}

namespace lf
{
	int a=200;
}

using namespace chh;

int main()
{
	//int a=300;
	cout<<a<<endl;
}

命名空间还可以嵌套使用 , 下面会打印出 group 里面的b.

#include<iostream>
using namespace std;

namespace group
{
	namespace one
	{
		int b=3;
	}
	namespace two
	{
		int b=2;
	}
	int b=1;
}

int main()
{
	cout<<group::b<<endl;
}

也可以引用 group 里面的 one 的命名空间 不过一般用的会很少 .

#include<iostream>
using namespace std;

namespace group
{
	namespace one
	{
		int b=3;
	}
	namespace two
	{
		int b=2;
	}
	int b=1;
}

int main()
{
	cout<<group::one::b<<endl;
}

猜你喜欢

转载自blog.csdn.net/Superman___007/article/details/82345638