【C++】名字空间(解决名字冲突问题二)

目录

名字空间定义

名字空间使用

头源分离

同一命名空间在多个文件中


 一般自己是不会使用的,但一些大型的库可能用到,比如命名空间std.

名字空间定义

解决名字冲突问题的究极解决方法:namespace(名字空间)

语法为:

namespace XXX
{
    //把类和函数写在这个大括号里面
    class YYY
    {
    };
} //这里不需要加分号

举一个简单的例子:

#include "stdafx.h"
#include <stdio.h>

namespace XXX
{
	void Test()
	{
		printf("hello world!\n");
	}
}

void Test()
{
	printf("I am second!\n");
}

int main()
{
	XXX::Test();
	Test();
    return 0;
}

有2个Test()函数,但是不会冲突,因为有了命名空间。

名字空间使用

如果觉得每次加上前缀麻烦,使用using关键字解除前缀。(但要确定名字不会冲突)

Test.h

#pragma once
#include <stdio.h>

namespace XXX
{
	void Test()
	{
		printf("hello world!\n");
	}
	class Object 
	{
	public:
		int x;
	public:
		void Print()
		{
			printf("Class Object.\n");
		}
	};
}

main.cpp

#include "stdafx.h"
#include <stdio.h>
#include "Test.h"

using namespace XXX;

int main()
{
	Test();
	Object a;
	return 0;
}

如果使用using namespace XXX;那么就会解除所有的XXX前缀。但是有时候不想解除所有的前缀,只想解除其中的某一个前缀,可以将main.cpp做出如下修改,就单纯解除了Object的前缀

#include "stdafx.h"
#include <stdio.h>
#include "Test.h"

using XXX::Object;

int main()
{
	XXX::Test();
	Object a;
	return 0;
}

头源分离

一般情况下我们会将Test.h中的函数拿出来实现,这时将Test.h修改为如下2个文件:Test.h和Test.cpp

Test.h

#pragma once
#include <stdio.h>

namespace XXX
{
	void Test();
	class Object 
	{
	public:
		int x;
	public:
		void Print();
	};
}

Test.cpp

#include "stdafx.h"
#include "Test.h"

////第一种方式
//void XXX::Test()
//{
//	printf("hello, world.\n");
//}
//
//void XXX::Object::Print()
//{
//	printf("Class Object.\n");
//}

namespace XXX
{
	void Test()
	{
		printf("hello, world.\n");
	}

	void Object::Print()
	{
		printf("Class Object.\n");
	}
}

main.cpp

#include "stdafx.h"
#include <stdio.h>
#include "Test.h"

using XXX::Object;

int main()
{
	XXX::Test();
	Object a;
	a.Print();
	return 0;
}

同一命名空间在多个文件中

Test.h

#pragma once
#include <stdio.h>

namespace XXX
{
	void Test();
	class Object 
	{
	public:
		int x;
	public:
		void Print();
	};
}

Test.cpp

#include "stdafx.h"
#include "Test.h"

////第一种方式
//void XXX::Test()
//{
//	printf("hello, world.\n");
//}
//
//void XXX::Object::Print()
//{
//	printf("Class Object.\n");
//}

namespace XXX
{
	void Test()
	{
		printf("hello, world.\n");
	}

	void Object::Print()
	{
		printf("Class Object.\n");
	}
}

Test2.h

#pragma once
class Test2
{
public:
	Test2();
	~Test2();
};

namespace XXX
{
	void Test2();
}

Test2.cpp

#include "stdafx.h"
#include "Test2.h"
#include <stdio.h>

Test2::Test2()
{
}


Test2::~Test2()
{
}


void XXX::Test2()
{
	printf("This is Test2.\n");
}

main.cpp

#include "stdafx.h"
#include <stdio.h>
#include "Test.h"
#include "Test2.h"

using XXX::Object;

int main()
{
	XXX::Test();
	Object a;
	a.Print();
	XXX::Test2();
	return 0;
}

猜你喜欢

转载自blog.csdn.net/u013066730/article/details/84619347