本文主要是介绍Cherno C++ P60 为什么我不使用using namespace std,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
YouTube视频链接
为什么我不使用using namespace std
本文是ChernoP60视频的学习笔记。
在之前的代码中,有很多实例使用了标准库中的东西。比如std::vector,std::cout,std::cin.get()等。每次使用标准库中的函数时,需要在前面输入std::。若在文件的上面加上using namespace std;就不用这么做了。
#include<iostream>
#include<vector>
#include<functional>
#include<algorithm>using namespace std;void ForEach(const vector<int>& values,const function<void(int)>& func)
{for (int value : values)func(value);
}int main()
{vector<int> values = { 1,5,4,2,3 };auto it = find_if(values.begin(), values.end(), [](int value) {return value > 3;});cout << *it << endl;int a = 5;auto lambda = [=](int value) mutable {a = 6; cout << " Value:" << a << endl;};ForEach(values, lambda);cin.get();
}
我们可以在函数内部局部声明它,比如在main函数中,意思是应用于这个作用域。
#include<iostream>
#include<vector>
#include<functional>
#include<algorithm>//仍需要std::
void ForEach(const std::vector<int>& values,const std::function<void(int)>& func)
{for (int value : values)func(value);
}int main()
{using namespace std;vector<int> values = { 1,5,4,2,3 };auto it = find_if(values.begin(), values.end(), [](int value) {return value > 3;});cout << *it << endl;int a = 5;auto lambda = [=](int value) mutable {a = 6;cout << " Value:" << a << endl;};ForEach(values, lambda);cin.get();
}
但是我们的原始代码很容易就能指出使用的是标准模板库和C++库,带有std前缀的来自于标准库,若使用using namespace std就会难分辨。如下代码
#include<iostream>
#include<string>namespace apple {void print(const std::string& text){std::cout << text << std::endl;}
}using namespace apple;int main()
{//apple::print("Hello");print("Hello");std::cin.get();
}
若又引入了一个库命名空间为orange,把text赋值到一个字符串中,然后把字符串倒过来再打印出来。现在print函数的麻烦来了,若同时使用using namespace apple;和using namespace orange;,哪一个会被调用呢?
它反向打印了文本,"Hello"是一个const char数组,它不是一个string。若没有orang命名空间,apple里可以做一个隐式转换,因为const char数组可以转换成string对象。当引入orange后,它的pring函数会更加匹配。这里就是const char*,不需要任何转换。
当使用这样的代码时,它会调用完全不同的函数。这不是一种编译错误而是无声的运行时错误。若不使用using namespace apple和orange,使用apple::print即可。
我们要注意避免在头文件内部使用using namespace。
这篇关于Cherno C++ P60 为什么我不使用using namespace std的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!