How come when using the string object for variables and parameters you need to have #include <string>
, but you don't need it for string literals? For example, you can say cout << "This is a string literal";
without #include <string>
.
I am learning C++ using a Deitel Brothers book and came up with this question when learning character arrays.
A string literal is not a std::string
object, it's an array of const char
.
"This is a string literal"
has the type const char[25]
.
In most situations – including this one – an array implicitly decays into a pointer to its first element, and there is an operator<<
overload for const char*
.
It's pretty confusing that "string" means several different things in C++, but after a while (and pulling of hair and gnashing of teeth) the intended meaning will be clear from context.
A string literal like "This is a string literal"
is of type const char[25]
, not of type std::string
. Statement cout << "This is a string literal"
actually calls operator <<(ostream&, const char*)
, and the string literal parameter decays to type const char*
. There isn't any std::string
involved in this case.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.