Joy*_*Joy 0 c++ string namespaces std
我在我的代码中使用了许多名称空间,包括std,所以当我想在我的代码中声明一个字符串变量时,我应该精确地使用std :: string或者我可以放置字符串:
#include <string.h>
using namespace std;
using namespace boost;
using namespace xerces;
int main()
{
/*! should I declare my str like this */
std::string str;
/*! or I can declare it like this */
string str1;
cout << str << str1 <<endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
既然你有using namespace std;,名字的string意思与std::string[*] 相同.因此,这是一个你喜欢的风格问题(如果你愿意,std::string你可以省略using namespace std;).
在std::和之间存在一些名称冲突boost::,特别是对于在标准化之前在Boost中进行过试验的事物.因此,举例来说,如果你有相应的头那么这两个std::shared_ptr和boost::shared_ptr存在.它们可能会也可能不会引用相同的类型,我没有检查Boost是否在定义标准类型之前尝试检测标准类型.
因此,同时使用两者std和boost命名空间并不一定是个好主意.您可以使用单个名称using std::string;,而不是整个命名空间.
[*]如果std::string已定义,则不是,因为您没有包含<string>.
你可以写string.但是,如果boost或者xerces还有符号string呢?我建议不要使用这些using指令.这不仅string可能发生冲突.您实质上是将大量符号拉入全局命名空间.如果你真的想避免输入std::那么你可以使用typedef:
typedef std::string MyStr;
Run Code Online (Sandbox Code Playgroud)