【C++】C++命名空间(名字空间)

例如小李和小韩都参与了一个文件管理系统的开发,它们都定义了一个全局变量 fp,用来指明当前打开的文件,将他们的代码整合在一起编译时,很明显编译器会提示 fp 重复定义(Redefinition)错误。

::是一个新符号,称为域解析操作符,在C++中用来指明要使用的命名空间。

除了直接使用域解析操作符,还可以采用 using 声明,例如:

using Li :: fp;

fp = fopen("one.txt", "r"); //使用小李定义的变量 fp

Han :: fp = fopen("two.txt", "rb+"); //使用小韩定义的变量 fp

在代码的开头用using声明了 Li::fp,它的意思是,using 声明以后的程序中如果出现了未指明命名空间的 fp,就使用 Li::fp;但是若要使用小韩定义的 fp,仍然需要 Han::fp。

参考程序(有改动和注释)

#include <stdio.h>

//将类定义在命名空间中
namespace wanglei{
	class Student{
	public:
		char *name;
		int age;
		float score;

	public:
		void say(){
			printf("%s的年龄是 %d,成绩是 %f\n", name, age, score);
		}
	};
}


namespace BeiJing{
	class Student{
	public:
		char *name;
		int age;
		float score;

	public:
		void say(){
			printf("%s的党龄是 %d,成绩是 %f\n", name, age, score);
		}
	};
}

int main(){
	wanglei::Student stu1;
	stu1.name = "小明";
	stu1.age = 15;
	stu1.score = 92.5f;
	stu1.say();



	BeiJing::Student stu2;		//只能写成  BeiJing::Student 或者  wanglei::Student,不能写成 BeiJing::Student stu1;
	//否则在同一个main函数里出现两个stu1  是重定义redefinition
	stu2.name = "小红";
	stu2.age = 15;
	stu2.score = 92.5f;
	stu2.say();


	return 0;
}

猜你喜欢

转载自blog.csdn.net/leiwangzhongde/article/details/82958116