std::string vs string in c++

Possible Duplicates:
Why is 'using namespace std;' considered a bad practice in C++?
Using std Namespace

Ive been hovering around a bunch of different forums and i seem to see this pop up every time and again. Its a very much beginner question.

I usually define a program with

#include<string>
using namespace std;

string x;

I see a bunch of code samples out there who define a string as

std::string.

What is the purpose of this? is it good practice or have some functionality?


As the other answer already stated, using std:: is necessary unless you import either the whole std namespace or std::string (see below).

In my opinion it's nicer to use std::string instead of string as it explicitely shows that it's a std::string and not some other string implementation.

If you prefer to write just string though, I'd suggest you to use using std::string; instead of using namespace std; to only import the things into the global namespace that you actually need.


The full name of string is std::string because it resides in namespace std , the namespace in which all of the C++ standard library functions, classes, and objects reside.

In your code, you've explicitly added the line using namespace std; , which lets you use anything from the standard namespace without using the std:: prefix. Thus you can refer to std::string (the real name of the string type) using the shorthand string since the compiler knows to look in namespace std for it.

There is no functionality difference between string and std::string because they're the same type. That said, there are times where you would prefer std::string over string . For example, in a header file, it is generally not considered a good idea to put the line using namespace std; (or to use any namespace, for that matter) because it can cause names in files that include that header to become ambiguous. In this setup, you would just #include <string> in the header, then use std::string to refer to the string type. Similarly, if there ever was any ambiguity between std::string and some other string type, using the name std::string would remove the ambiguity.

Whether or not you include the line using namespace std; at all is a somewhat contested topic and many programmers are strongly for or strongly against it. I suggest using whatever you're comfortable with and making sure to adopt whatever coding conventions are used when working on a large project.


As ssteinberg said it is the same. But only syntactically.

From my experience, it is more useful to either use the full name

std::string 

wherever you need it, or add an explicit

using std::string;

in the beginning of your source file.

The advantage is that in this way the dependencies of your source file are more observable. If you add a

using namespace std;

it means that your code may depend on anything within that namespace.

链接地址: http://www.djcxy.com/p/29778.html

上一篇: 是使用命名空间..就像坏?

下一篇: std :: string vs c ++中的字符串