Isn't string equals to const char *?
I am reading some documents about c++ and it says:In c++ string is equals to const char *.Is this true?
Because i compile this code:
Code:
#include <iostream>
#include <string>
using namespace std;
int main() {
const char * p="ppppp";
string s="aaaaaaaa";
s+="eeeee";
s=p;
p=s;//gives error:error C2440: '=' : cannot convert from 'std::string' to 'const char *'
}
Isn't string equals to const char *?If equals why does this error occur and why does compiler give permission to change value of string s after initializition?
Re: Isn't string equals to const char *?
"String" is a term often used to refer to a char* pointing to a zero-terminated sequence of chars, and this is quite safe usage in C. In C++, however, there is a class (in the std namespace) called string, and this is not the same thing, so we usually refer to "C strings" to differentiate the two. The string class does provide automatic conversion to create an object from char* pointers, but the converse (std::string to char*) is not automatic - there's a member function called c_str() to do the job. You can correct the compilation error by putting
Re: Isn't string equals to const char *?
sawer, you should use C++ strings everywhere, except if you have a very good reason not to do so.
C++ strings are much easier to use and much safer.
Actually, C strings (char*) are not managed automatically, but are plain pointer to chars.
It means that to append two char*, you must allocate memory dynamically (with new[], malloc or perhaps std::vector), and, then copy the characters to the new char*.
C++ strings are much more like strings of other languages.
char* are not true strings... they are just pointers to arrays of characters.
Re: Isn't string equals to const char *?
Quote:
Originally Posted by sawer
I am reading some documents about c++ and it says:In c++ string is equals to const char *.
May I recommend throwing that document away ;).
What it probably meant to say is: In C, strings are represented by const char*.