This question already has answers here:
Closed 3 years ago.
In order to use strings I need to include the string header, so that its implementation becomes available. But if that is so, why do I still need to add the line using std::string
?
Why doesn't it already know about the string data type?
#include <string>
using std::string;
int main() {
string s1;
}
Because string
is defined within namespace called std
.
you can write std::string
everywhere where <string>
is included but you can add using std::string
and don't use namespace in the scope (so std::string
might be reffered to as string
). You can place it for example inside the function and then it applies only to that function:
#include <string>
void foo() {
using std::string;
string a; //OK
}
void bar() {
std::string b; //OK
string c; //ERROR: identifier "string" is undefined
}
using std::string;
doesn't mean you can now use this type, but you can use this type without having to specify the namespace std::
before the name of the type.
The following code is correct:
#include <string>
int main()
{
std::string s1;
return 0;
}
Because the declaration of class string
is in the namespace std. Thus you either need to always access it via std::string (then you don't need to have using) or do it as you did.
Namespace
is an additional feature of C++, which is defining the scope of a variable, function or object and avoiding the name collision. Here, the string
object is defined in the std
namespace.
std
is the standard namespace. cout
, cin
, string
and a lot of other things are defined in it.
The header <string>
declares the various entities related to the strings library, whereas namespaces are used to group related functionality and allow use of the same names in different namespaces.