#为什么我们不能使用"using namespace std"

为什么我们不能使用"using namespace std"

相信很多的cpp初学者都在开始编写程序的时候喜欢使用using namespace std,因为这样我们可以在写标准库的东西的时候不用每个都去加一个例如std::cout,然而到了后面,我们又看到不要使用using namespace std,给出的原因一般都是你只是需要你现在的那些标准库的东西,但是你却释放了全部。这样的解释确实是的,但是还有另一种解释,我觉得这种解释才是在项目里面为何不要使用using namespace std
我们现在先看一段代码

namespace apple {
	void print(const std::string& text)
	{
		std::cout << text << std::endl;
	}
}

namespace orange {
	void print(const char* text)
	{
		std::string temp = text;
		std::reverse(temp.begin(), temp.end());
		std::cout << temp << std::endl;
	}
}

int main() {

	apple::print("Hello");
	orange::print("Hello");
}

我们自己创建了自己的namespace,如果我们运行这段代码,我们会得到一个Hello,而另一个是olleH,是的这样没有问题,但是我们将其中main函数中的apple以及orange删除,并且使用using namespace apple/orange,且只留下一个调用。如下

namespace apple {
	void print(const std::string& text)
	{
		std::cout << text << std::endl;
	}
}

namespace orange {
	void print(const char* text)
	{
		std::string temp = text;
		std::reverse(temp.begin(), temp.end());
		std::cout << temp << std::endl;
	}
}
using namespace apple;
using namespace orange;

int main() {

print("Hello");

}

那么这次的运行,我们会调用orange里面的print因为相对于string,”Hello“本身是const char*类型,所以会适配更好的函数,假如我们删去orange,才会通过隐式转换调用apple。
相信通过这个例子,我们已经知道为什么,不要使用using namespace std;,因为在项目中,我们会创建自己的命名空间,而这时候我们假如在自己的命名空间里面创建了一个跟标准库里面一样的函数,那么我们的代码就会产生歧义,而歧义大部分是伴随着Bug的,所以指明我们调用的到底是哪个命名空间的很有必要,不仅仅是为了减少Bug,也是为了在调试阶段能够有着更好的可读性。

posted @ 2020-03-17 15:54  Yekko  阅读(349)  评论(0编辑  收藏  举报