我已经告诉别人,编写using namespace std;代码是错误的,我应该用std::cout和std::cin直接代替.
为什么被using namespace std;认为是不好的做法?是低效还是冒着声明模糊变量(与名称std空间中的函数具有相同名称的变量)的风险?它会影响性能吗?
关于std命名空间使用'using'似乎有不同的看法.
有人说使用' using namespace std',其他人说不要,而是先加上与' std::' 一起使用的std函数,而其他人则说使用这样的东西:
using std::string;
using std::cout;
using std::cin;
using std::endl;
using std::vector;
Run Code Online (Sandbox Code Playgroud)
对于要使用的所有std函数.
各自的优点和缺点是什么?
有一天,当我问一个问题有人回答道说,如果有人问一个问题,告诉他们正确的方式做到这一点,而不是using namespace std;,我认为是有点怪,因为using namespace std;是方式更容易,但我想我没有现在的我是一个'初学者'编码员,你们知道的更好.
所以我想我的问题是:为什么std::而不是using namespace std;?
谢谢.
在案例1中,当我初始化这样的字符串时,输出为空:
#include <iostream>
#include<string>
using namespace std;
//CODE 1
int main()
{
string s="hello" + 'c';
cout<<s<<endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但是当我以这种方式写它时它工作正常:
#include <iostream>
#include<string>
using namespace std;
//CODE 2
int main()
{
string s="hello";
char k='c';
s+=k;
cout<<s<<endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
现在我很困惑,因为在堆栈溢出问的另一个问题上它说当使用命名空间std时字符串和std :: string之间没有区别,那些答案通过说- > 字符串和std之间没有功能区别: :string因为它们 在c ++中与std :: string vs string 类型相同, 而为这个问题提供的答案指出了不同之处:
编译器是g ++(GCC)4.8.5 20150623(Red Hat 4.8.5-4)