I don't suppose anyone tell me whats the difference between using the std::string and just the string data type in C++??
In what situation should the std::string should be used over开发者_Python百科 the standard string??
Thanks.
They're both the same type. std::string
specifies the namespace, while string
only makes sense if a using namespace std;
or using std::string
statement is used. So it doesn't make any difference what you use (as long as you're consistent).
If you're talking about the string literals (such as "hello"
), then they're of type const char []
, that implicitly decays in a const char *
. std::string
has a non-explicit
constructor that takes a const char *
, this allowing implicit conversion from const char *
to std::string
. The opposite operation can be done with the std::string::c_str()
method.
If you're looking for a reason to use std::string
instead of const char *
, then I guess my answer would be "as much as you can".
These are likely the same thing within your program. The "standard" string resides within the "std" namespace. If you are "using std::string;" or "using namespace std;" within the module, then they are equivalent. If you aren't specifying a "using" statement, then you are required to provide the namespace of the object. It's preferable to not provide "using" statements within the header file and therefore you will typically see namespace resolution/specifiers on objects. (i.e. std::vector, mynamespace::myclass, etc.). The use of "using" is more common in implementation files where they won't affect other files as they would if specified in a header file.
It's possible to use a string object from another provider. In this case the provider would/should have their string object implementation in their own namespace and you would need to declare which string object you were using.
So:
File: stdString.cpp
-------------
#include <string>
#include "providerx/string.h"
using namespace std;
void foo()
{
string x; // Using string object provided by the C++ standard library
std::string y; // Again, using C++ standard lib string
providerx::string // Using string object defined within the providerx namespace
}
File: providerString.cpp
-------------------
#include "providerx/string.h"
using providerX::string;
void foo()
{
string x; // Using providerx string object
}
Most likely, you have using namespace std
somewhere in your code. This is allowing you to access members of the std namespace without resolving the scope. Therefore...
std::string == string
精彩评论